Пример #1
0
  /**
   * @param request
   * @return
   * @throws IOException
   * @throws HttpExecuteException
   * @throws MalformedURLException
   */
  private HttpResponse executeRequest(HttpRequest request) throws IOException {
    if (request.shouldIgnoreResponse()) return new HttpResponse();
    if (!request.hasHeader("Host")) throw new HttpExecuteException("HTTP Host not set");
    String host = request.getHeader("Host").get(0);

    URL url = new URL("http", host, 80, request.getPath());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(request.getMethod());
    for (Entry<String, List<String>> entry : request.getHeaderPairs().entrySet()) {
      for (String value : entry.getValue()) connection.addRequestProperty(entry.getKey(), value);
    }
    if (request.getMethod().equals("POST")) {
      // Write post data if it exists
      connection.getOutputStream().write(request.getContent());
    }

    HttpResponse response = new HttpResponse();
    response.setResponseCode(connection.getResponseCode());
    response.setResponseMessage(connection.getResponseMessage());
    for (Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
      for (String value : entry.getValue()) response.addHeader(entry.getKey(), value);
    }
    // responseType is eg. the 4 in 403
    int responseType = response.getResponseCode() / 100;
    if (responseType == 4 || responseType == 5)
      response.readAllContent(connection.getErrorStream());
    else response.readAllContent(connection.getInputStream());

    // Add Network Spoofer fingerprint
    response.addHeader("X-Network-Spoofer", "ON");

    return response;
  }
Пример #2
0
 protected HttpResponse newHttpResponse(HttpMessageBuffer msg, HttpResponseException e) {
   HttpResponse httpRsp = e.toHttpResponse(msg.getHttpVersionString());
   if (msg.getHttpVersion() > 1.0) {
     httpRsp.addHeader(HttpConstants.Headers.HOST, this.headerHostValue);
   }
   httpRsp.addHeader(HttpConstants.Headers.SERVER, this.getServerName());
   httpRsp.addHeader(HttpConstants.Headers.CONNECTION, "close");
   return httpRsp;
 }
Пример #3
0
 @Override
 protected void doService(HttpRequest request, HttpResponse response, HttpContext context)
     throws HttpException, IOException {
   response.addHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate"); // Disable caching
   // Normalize the URI
   super.doService(request, response, context);
 }
Пример #4
0
  protected static void addToResponse(Response response, HttpResponse nettyResponse) {
    Map<String, Http.Header> headers = response.headers;
    for (Map.Entry<String, Http.Header> entry : headers.entrySet()) {
      Http.Header hd = entry.getValue();
      for (String value : hd.values) {
        nettyResponse.setHeader(entry.getKey(), value);
      }
    }
    Map<String, Http.Cookie> cookies = response.cookies;

    for (Http.Cookie cookie : cookies.values()) {
      CookieEncoder encoder = new CookieEncoder(true);
      Cookie c = new DefaultCookie(cookie.name, cookie.value);
      c.setSecure(cookie.secure);
      c.setPath(cookie.path);
      if (cookie.domain != null) {
        c.setDomain(cookie.domain);
      }
      if (cookie.maxAge != null) {
        c.setMaxAge(cookie.maxAge);
      }
      c.setHttpOnly(cookie.httpOnly);
      encoder.addCookie(c);
      nettyResponse.addHeader(SET_COOKIE, encoder.encode());
    }

    if (!response.headers.containsKey(CACHE_CONTROL)) {
      nettyResponse.setHeader(CACHE_CONTROL, "no-cache");
    }
  }
Пример #5
0
 protected HttpResponse newHttpResponse(
     HttpMessageBuffer origMsg, int statusCode, String reasonPhrase, Encoding encoding) {
   Encoding responseEncoding = null;
   if (this.encodeResponses) {
     responseEncoding = encoding;
   }
   HttpResponse httpRsp;
   if (origMsg == null) {
     httpRsp = new HttpResponse(statusCode, reasonPhrase, responseEncoding);
   } else {
     httpRsp =
         new HttpResponse(
             origMsg.getHttpVersionString(), statusCode, reasonPhrase, responseEncoding);
   }
   if (origMsg.getHttpVersion() > 1.0) {
     httpRsp.addHeader(HttpConstants.Headers.HOST, this.headerHostValue);
   }
   httpRsp.addHeader(HttpConstants.Headers.SERVER, this.getServerName());
   return httpRsp;
 }
Пример #6
0
 /**
  * Constructs a new {@link HttpResponse} containing the given XML-RPC method response.
  *
  * <p>This implementation encodes the response using <code>UTF-8</code>, sets the status code to
  * <code>200</code>, and sets <code>Content-Type</code> header to <code>text/xml</code> as
  * required. No other headers are set.
  *
  * @param methodRsp The XML-RPC method response to be returned in the HTTP response.
  * @param encoding An {@link Encoding} describing the encoding to use when constructing this
  *     message. This also informs the <code>Content-Encoding</code> header value. May be <code>
  *     null</code>.
  * @return A new {@link HttpResponse} with the marshalled XML-RPC response as its content.
  * @throws IOException if an error occurs while marshalling the XML-RPC response.
  * @throws MarshallingException
  */
 protected HttpResponse toHttpResponse(
     HttpMessageBuffer origMsg, RpcResponse methodRsp, Encoding encoding)
     throws IOException, MarshallingException {
   ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
   methodRsp.marshal(byteOs, Charset.forName("UTF-8"));
   byte[] rspXml = byteOs.toByteArray();
   HttpResponse httpRsp = this.newHttpResponse(origMsg, 200, "OK", encoding);
   httpRsp.addHeader(HttpConstants.Headers.CONTENT_TYPE, methodRsp.getContentType());
   httpRsp.setContent(rspXml);
   return httpRsp;
 }
Пример #7
0
  public void handle(Socket socket) {
    InputStream input = null;
    OutputStream output = null;

    try {
      input = socket.getInputStream();
      output = socket.getOutputStream();

      // 创建请求对象
      request = new HttpRequest(input);

      // 创建响应对象
      response = new HttpResponse(output);
      response.setRequest(request);

      // 设置响应头
      response.addHeader("Server", "Bradypod Server Container");
      response.addHeader("Content-Type", "text/html");

      // 解析请求
      request.parse();

      response.sendHeaders(); // 发送响应头

      // 判断是否请求动态资源
      if (request.getRequestURI() == null) {
        response.getWriter().println("404 Not Found!");
      } else if (request.getRequestURI().startsWith("/servlet/")) {
        ServletProcessor processor = new ServletProcessor();
        processor.process(request, response);
      } else {
        ResourceProcessor processor = new ResourceProcessor();
        processor.process(request, response);
      } // --> end if-else

      // 关闭连接
      socket.close();
    } catch (IOException ex) {

    }
  }
  /**
   * Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
   * handler object.
   *
   * @param method The HTTP method that was invoked to get the response.
   * @param request The HTTP request associated with the response.
   * @return The new, initialized HttpResponse object ready to be passed to an HTTP response handler
   *     object.
   * @throws IOException If there were any problems getting any response information from the
   *     HttpClient method object.
   */
  private HttpResponse createResponse(
      HttpRequestBase method, Request<?> request, org.apache.http.HttpResponse apacheHttpResponse)
      throws IOException {
    HttpResponse httpResponse = new HttpResponse(request, method);

    if (apacheHttpResponse.getEntity() != null) {
      httpResponse.setContent(apacheHttpResponse.getEntity().getContent());
    }

    httpResponse.setStatusCode(apacheHttpResponse.getStatusLine().getStatusCode());
    httpResponse.setStatusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
    for (Header header : apacheHttpResponse.getAllHeaders()) {
      httpResponse.addHeader(header.getName(), header.getValue());
    }

    return httpResponse;
  }
Пример #9
0
  public HttpResponse getResponse(HttpRequestHeader hdr) {
    Log.i(LOG_TAG, " getResponse() started");

    HttpResponse response;

    if (hdr.getHeaderParams() == null) {
      Log.e(LOG_TAG, "No header params found in request");
      return new HttpResponse(HttpResponse.HTTP_BADREQUEST, "No header params found in request");
    }

    String method = hdr.getHeaderParams().getProperty("method");

    if (method == null) {
      Log.e(LOG_TAG, "No method in request headers");
      return new HttpResponse(HttpResponse.HTTP_BADREQUEST, "No method in request headers");
    }

    if (!method.equalsIgnoreCase("GET")) {
      Log.e(LOG_TAG, "getResponse() - only GET supported");
      return new HttpResponse(HttpResponse.HTTP_NOTIMPLEMENTED, method + " not supported");
    }

    String filename = hdr.getHeaderParams().getProperty("uri");

    if (filename == null
        || filename.startsWith("..")
        || filename.endsWith("..")
        || filename.indexOf("../") >= 0) {
      Log.e(LOG_TAG, "getResponse() - file not found");

      return new HttpResponse(HttpResponse.HTTP_FORBIDDEN, "Relative paths not allowed");
    }

    try {
      String mime = "";
      ContentInputStreamAdapter.ContentInputStream responseData =
          inputStreamAdapter.getContentInputStream(filename);

      if (responseData == null) {
        return new HttpResponse(HttpResponse.HTTP_NOTFOUND, "File not found");
      }

      long startFrom = -1;
      long endAt = -1;
      String range = hdr.getHeaderParams().getProperty("range");

      if (range != null) {
        Log.i(LOG_TAG, "Request contains a range: " + range);

        if (range.startsWith("bytes=")) {
          range = range.substring("bytes=".length());
          int minus = range.indexOf('-');
          try {
            if (minus > 0) {
              startFrom = Long.parseLong(range.substring(0, minus));
              endAt = Long.parseLong(range.substring(minus + 1));
            }
          } catch (NumberFormatException nfe) {
            Log.w(LOG_TAG, "Non Fatal Error extracting range :" + range, nfe);
            startFrom = -1;
            endAt = -1;
          }
        }
      }

      if (startFrom >= 0) {
        if (startFrom >= responseData.contentLength) {
          response =
              new HttpResponse(
                  HttpResponse.HTTP_RANGE_NOT_SATISFIABLE, HttpResponse.MIME_PLAINTEXT, "");
          response.addHeader("Content-Range", "bytes 0-0/" + responseData.contentLength);

          if (mime.startsWith("application/")) {
            response.addHeader(
                "Content-Disposition", "attachment; filename=\"" + responseData.filename + "\"");
          }
        } else {
          response =
              new HttpResponse(
                  HttpResponse.HTTP_PARTIALCONTENT, responseData.mime, responseData.content);

          if (endAt < 0) {
            endAt = responseData.contentLength - 1;
          }

          long length = endAt - startFrom + 1;
          if (length < 0) {
            length = 0;
          }

          if (startFrom > 0) {
            responseData.content.skip(startFrom);
          }

          response.addHeader("Content-Length", "" + length);
          response.addHeader(
              "Content-Range",
              "bytes " + startFrom + "-" + endAt + "/" + responseData.contentLength);
        }
      } else {
        response = new HttpResponse(HttpResponse.HTTP_OK, responseData.mime, responseData.content);
        response.addHeader("Content-Length", "" + responseData.contentLength);
        response.addHeader("Accept-Ranges", "bytes");
      }

      response.addHeader("Original-Length", "" + responseData.contentLength);
      response.addHeader(
          "Last-Modified", dateFormatter.format(new Date(responseData.lastModifiedDate)));
    } catch (IOException ioe) {
      response =
          new HttpResponse(HttpResponse.HTTP_INTERNALERROR, "IOException: " + ioe.getMessage());
      Log.e(LOG_TAG, "Error Reading file", ioe);
    }

    response.addHeader("Date", dateFormatter.format(new Date()));
    response.addHeader("Content-Type", "audio/x-m4a");
    response.addHeader("Connection", "close");
    response.addHeader("Cache-Control", "no-cache");
    response.addHeader("Expires", "-1");
    response.addHeader("Pragma", "no-cache");

    Log.i(LOG_TAG, " getResponse() ended. Response = " + response);

    return response;
  }
Пример #10
0
  // TODO: add request and response as parameter
  public static void serve500(Exception e, ChannelHandlerContext ctx, HttpRequest nettyRequest) {
    Logger.trace("serve500: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    if (exposePlayServer) {
      nettyResponse.setHeader(SERVER, signature);
    }

    Request request = Request.current();
    Response response = Response.current();

    try {
      if (!(e instanceof PlayException)) {
        e = new play.exceptions.UnexpectedException(e);
      }

      // Flush some cookies
      try {

        Map<String, Http.Cookie> cookies = response.cookies;
        for (Http.Cookie cookie : cookies.values()) {
          CookieEncoder encoder = new CookieEncoder(true);
          Cookie c = new DefaultCookie(cookie.name, cookie.value);
          c.setSecure(cookie.secure);
          c.setPath(cookie.path);
          if (cookie.domain != null) {
            c.setDomain(cookie.domain);
          }
          if (cookie.maxAge != null) {
            c.setMaxAge(cookie.maxAge);
          }
          c.setHttpOnly(cookie.httpOnly);
          encoder.addCookie(c);
          nettyResponse.addHeader(SET_COOKIE, encoder.encode());
        }

      } catch (Exception exx) {
        Logger.error(e, "Trying to flush cookies");
        // humm ?
      }
      Map<String, Object> binding = getBindingForErrors(e, true);

      String format = request.format;
      if (format == null) {
        format = "txt";
      }

      nettyResponse.setHeader(
          "Content-Type", (MimeTypes.getContentType("500." + format, "text/plain")));
      try {
        String errorHtml = TemplateLoader.load("errors/500." + format).render(binding);

        ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
        nettyResponse.setContent(buf);
        ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        Logger.error(
            e, "Internal Server Error (500) for request %s", request.method + " " + request.url);
      } catch (Throwable ex) {
        Logger.error(
            e, "Internal Server Error (500) for request %s", request.method + " " + request.url);
        Logger.error(ex, "Error during the 500 response generation");
        try {
          ChannelBuffer buf =
              ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
          nettyResponse.setContent(buf);
          ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
          writeFuture.addListener(ChannelFutureListener.CLOSE);
        } catch (UnsupportedEncodingException fex) {
          Logger.error(fex, "(utf-8 ?)");
        }
      }
    } catch (Throwable exxx) {
      try {
        ChannelBuffer buf =
            ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
        nettyResponse.setContent(buf);
        ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
      } catch (Exception fex) {
        Logger.error(fex, "(utf-8 ?)");
      }
      if (exxx instanceof RuntimeException) {
        throw (RuntimeException) exxx;
      }
      throw new RuntimeException(exxx);
    }
    Logger.trace("serve500: end");
  }
Пример #11
0
  private void websocketHandshake(final ChannelHandlerContext ctx, HttpRequest req, MessageEvent e)
      throws Exception {

    // Create the WebSocket handshake response.
    HttpResponse res =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
    res.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
    res.addHeader(CONNECTION, HttpHeaders.Values.UPGRADE);

    // Fill in the headers and contents depending on handshake method.
    if (req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2)) {
      // New handshake method with a challenge:
      res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
      res.addHeader(
          SEC_WEBSOCKET_LOCATION, "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri());
      String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
      if (protocol != null) {
        res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
      }

      // Calculate the answer of the challenge.
      String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
      String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
      int a =
          (int)
              (Long.parseLong(key1.replaceAll("[^0-9]", ""))
                  / key1.replaceAll("[^ ]", "").length());
      int b =
          (int)
              (Long.parseLong(key2.replaceAll("[^0-9]", ""))
                  / key2.replaceAll("[^ ]", "").length());
      long c = req.getContent().readLong();
      ChannelBuffer input = ChannelBuffers.buffer(16);
      input.writeInt(a);
      input.writeInt(b);
      input.writeLong(c);
      try {
        ChannelBuffer output =
            ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(input.array()));
        res.setContent(output);
      } catch (NoSuchAlgorithmException ex) {
        throw new UnexpectedException(ex);
      }
    } else {
      // Old handshake method with no challenge:
      res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
      res.addHeader(
          WEBSOCKET_LOCATION, "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri());
      String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
      if (protocol != null) {
        res.addHeader(WEBSOCKET_PROTOCOL, protocol);
      }
    }

    // Keep the original request
    Http.Request request = parseRequest(ctx, req);

    // Route the websocket request
    request.method = "WS";
    Map<String, String> route = Router.route(request.method, request.path);
    if (!route.containsKey("action")) {
      // No route found to handle this websocket connection
      ctx.getChannel()
          .write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
      return;
    }

    // Upgrade the connection and send the handshake response.
    ChannelPipeline p = ctx.getChannel().getPipeline();
    p.remove("aggregator");
    p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());

    // Connect
    ctx.getChannel().write(res);

    p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
    req.setMethod(new HttpMethod("WEBSOCKET"));

    // Inbound
    Http.Inbound inbound =
        new Http.Inbound() {

          @Override
          public boolean isOpen() {
            return ctx.getChannel().isOpen();
          }
        };
    channels.put(ctx, inbound);

    // Outbound
    Http.Outbound outbound =
        new Http.Outbound() {

          final List<ChannelFuture> writeFutures =
              Collections.synchronizedList(new ArrayList<ChannelFuture>());
          Promise<Void> closeTask;

          synchronized void writeAndClose(ChannelFuture writeFuture) {
            if (!writeFuture.isDone()) {
              writeFutures.add(writeFuture);
              writeFuture.addListener(
                  new ChannelFutureListener() {

                    public void operationComplete(ChannelFuture cf) throws Exception {
                      writeFutures.remove(cf);
                      futureClose();
                    }
                  });
            }
          }

          void futureClose() {
            if (closeTask != null && writeFutures.isEmpty()) {
              closeTask.invoke(null);
            }
          }

          @Override
          public void send(String data) {
            if (!isOpen()) {
              throw new IllegalStateException("The outbound channel is closed");
            }
            writeAndClose(ctx.getChannel().write(new DefaultWebSocketFrame(data)));
          }

          @Override
          public void send(byte opcode, byte[] data, int offset, int length) {
            if (!isOpen()) {
              throw new IllegalStateException("The outbound channel is closed");
            }
            writeAndClose(
                ctx.getChannel()
                    .write(new DefaultWebSocketFrame(opcode, wrappedBuffer(data, offset, length))));
          }

          @Override
          public synchronized boolean isOpen() {
            return ctx.getChannel().isOpen() && closeTask == null;
          }

          @Override
          public synchronized void close() {
            closeTask = new Promise<Void>();
            closeTask.onRedeem(
                new Action<Promise<Void>>() {

                  public void invoke(Promise<Void> completed) {
                    writeFutures.clear();
                    ctx.getChannel().disconnect();
                    closeTask = null;
                  }
                });
            futureClose();
          }
        };

    Invoker.invoke(new WebSocketInvocation(route, request, inbound, outbound, ctx, e));
  }
Пример #12
0
    protected HttpResponse doRequest(HttpRequest request, RequestLine requestLine)
        throws IOException, MuleException {
      Map headers = parseHeaders(request);

      // TODO Mule 2.0 generic way to set stream message adapter
      MessageAdapter adapter = buildStandardAdapter(request, headers);

      MuleMessage message = new DefaultMuleMessage(adapter);

      String path = (String) message.getProperty(HttpConnector.HTTP_REQUEST_PROPERTY);
      int i = path.indexOf('?');
      if (i > -1) {
        path = path.substring(0, i);
      }

      message.setProperty(HttpConnector.HTTP_REQUEST_PATH_PROPERTY, path);

      if (logger.isDebugEnabled()) {
        logger.debug(message.getProperty(HttpConnector.HTTP_REQUEST_PROPERTY));
      }

      message.setProperty(
          HttpConnector.HTTP_CONTEXT_PATH_PROPERTY,
          HttpConnector.normalizeUrl(endpoint.getEndpointURI().getPath()));

      // determine if the request path on this request denotes a different receiver
      MessageReceiver receiver = getTargetReceiver(message, endpoint);

      HttpResponse response;
      // the response only needs to be transformed explicitly if
      // A) the request was not served or B) a null result was returned
      if (receiver != null) {
        preRouteMessage(message);
        MuleMessage returnMessage = receiver.routeMessage(message, endpoint.isSynchronous(), null);

        Object tempResponse;
        if (returnMessage != null) {
          tempResponse = returnMessage.getPayload();
        } else {
          tempResponse = NullPayload.getInstance();
        }
        // This removes the need for users to explicitly adding the response transformer
        // ObjectToHttpResponse in their config
        if (tempResponse instanceof HttpResponse) {
          response = (HttpResponse) tempResponse;
        } else {
          response = transformResponse(returnMessage);
        }

        response.disableKeepAlive(!((HttpConnector) connector).isKeepAlive());

        // Check if endpoint has a keep-alive property configured. Note the translation from
        // keep-alive in the schema to keepAlive here.
        boolean endpointOverride = Boolean.parseBoolean((String) endpoint.getProperty("keepAlive"));

        Header connectionHeader = request.getFirstHeader("Connection");
        if (connectionHeader != null) {
          String value = connectionHeader.getValue();
          if ("keep-alive".equalsIgnoreCase(value) && !endpointOverride) {
            response.setKeepAlive(true);
            Header header =
                new Header(
                    HttpConstants.HEADER_KEEP_ALIVE,
                    "timeout=" + ((HttpConnector) connector).getKeepAliveTimeout());
            response.addHeader(header);
          } else if ("close".equalsIgnoreCase(value)) {
            response.setKeepAlive(false);
          } else if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            response.setKeepAlive(true);
          } else {
            response.setKeepAlive(false);
          }
        }
      } else {
        response = buildFailureResponse(requestLine, message);
      }
      return response;
    }