Пример #1
0
  private static FullHttpRequest createHttpRequest(int spdyVersion, SpdyHeaderBlock requestFrame)
      throws Exception {
    // Create the first line of the request from the name/value pairs
    HttpMethod method = SpdyHeaders.getMethod(spdyVersion, requestFrame);
    String url = SpdyHeaders.getUrl(spdyVersion, requestFrame);
    HttpVersion httpVersion = SpdyHeaders.getVersion(spdyVersion, requestFrame);
    SpdyHeaders.removeMethod(spdyVersion, requestFrame);
    SpdyHeaders.removeUrl(spdyVersion, requestFrame);
    SpdyHeaders.removeVersion(spdyVersion, requestFrame);

    FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, url);

    // Remove the scheme header
    SpdyHeaders.removeScheme(spdyVersion, requestFrame);

    if (spdyVersion >= 3) {
      // Replace the SPDY host header with the HTTP host header
      String host = SpdyHeaders.getHost(requestFrame);
      SpdyHeaders.removeHost(requestFrame);
      HttpHeaders.setHost(req, host);
    }

    for (Map.Entry<String, String> e : requestFrame.headers().entries()) {
      req.headers().add(e.getKey(), e.getValue());
    }

    // The Connection and Keep-Alive headers are no longer valid
    HttpHeaders.setKeepAlive(req, true);

    // Transfer-Encoding header is not valid
    req.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);

    return req;
  }
 @Test
 public void clientRequestMultipleEmptyDataFrames() throws Exception {
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
Пример #3
0
 private void checkSession(Channel channel) {
   String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
   if (cookieString != null) {
     Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
     if (!cookies.isEmpty()) {
       for (Cookie elt : cookies) {
         if (elt.name().equalsIgnoreCase(R66SESSION + Configuration.configuration.getHOST_ID())) {
           logger.debug("Found session: " + elt);
           admin = elt;
           R66Session session = sessions.get(admin.value());
           if (session != null) {
             authentHttp = session;
             authentHttp.setStatus(73);
           } else {
             admin = null;
             continue;
           }
         } else if (elt.name().equalsIgnoreCase(I18NEXT)) {
           logger.debug("Found i18next: " + elt);
           lang = elt.value();
         }
       }
     }
   }
   if (admin == null) {
     logger.debug("NoSession: " + uriRequest + ":{}", admin);
   }
 }
 private static String getContentType(final FullHttpRequest request) {
   final String contentType = request.headers().get(CONTENT_TYPE);
   if (contentType == null) {
     return Transports.CONTENT_TYPE_PLAIN;
   }
   return contentType;
 }
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    FullHttpRequest req = (FullHttpRequest) msg;
    String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
    if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(req.getUri(), null, false);
      WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
      if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
      } else {
        ChannelFuture future = handshaker.handshake(ctx.channel(), req);
        future.addListener(
            f -> {
              this.configurator.switchToWebSockets(ctx.pipeline());
            });
      }
    } else {
      ReferenceCountUtil.retain(msg);
      this.configurator.switchToPlainHttp(ctx.pipeline());
      ChannelHandlerContext agg = ctx.pipeline().context(HttpObjectAggregator.class);
      agg.fireChannelRead(msg);
    }
  }
  private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req =
        ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(
                HTTP_1_1,
                HttpMethod.GET,
                "/chat",
                Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(HttpHeaderNames.HOST, "server.example.com");
    req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
    req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    if (subProtocol) {
      new WebSocketServerHandshaker00("ws://example.com/chat", "chat", Integer.MAX_VALUE)
          .handshake(ch, req);
    } else {
      new WebSocketServerHandshaker00("ws://example.com/chat", null, Integer.MAX_VALUE)
          .handshake(ch, req);
    }

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals(
        "ws://example.com/chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION));

    if (subProtocol) {
      Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    } else {
      Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    }
    LastHttpContent content = ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.release();
  }
 private static String getWebSocketLocation(FullHttpRequest req) {
   String location = req.headers().get(HOST) + WEBSOCKET_PATH;
   if (WebSocketServer.SSL) {
     return "wss://" + location;
   } else {
     return "ws://" + location;
   }
 }
Пример #8
0
 private void handleCookies(HttpResponse response) {
   String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
   boolean i18nextFound = false;
   if (cookieString != null) {
     Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
     if (!cookies.isEmpty()) {
       // Reset the sessions if necessary.
       boolean findSession = false;
       for (Cookie cookie : cookies) {
         if (cookie
             .name()
             .equalsIgnoreCase(R66SESSION + Configuration.configuration.getHOST_ID())) {
           if (newSession) {
             findSession = false;
           } else {
             findSession = true;
             response
                 .headers()
                 .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
           }
         } else if (cookie.name().equalsIgnoreCase(I18NEXT)) {
           i18nextFound = true;
           cookie.setValue(lang);
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
         } else {
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
         }
       }
       if (!i18nextFound) {
         Cookie cookie = new DefaultCookie(I18NEXT, lang);
         response
             .headers()
             .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
       }
       newSession = false;
       if (!findSession) {
         if (admin != null) {
           response
               .headers()
               .add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(admin));
           logger.debug("AddSession: " + uriRequest + ":{}", admin);
         }
       }
     }
   } else {
     Cookie cookie = new DefaultCookie(I18NEXT, lang);
     response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie));
     if (admin != null) {
       logger.debug("AddSession: " + uriRequest + ":{}", admin);
       response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(admin));
     }
   }
 }
 @Override
 public FullHttpMessage copyIfNeeded(FullHttpMessage msg) {
   if (msg instanceof FullHttpRequest) {
     FullHttpRequest copy = ((FullHttpRequest) msg).copy(null);
     copy.headers().remove(HttpHeaderNames.EXPECT);
     return copy;
   }
   return null;
 }
Пример #10
0
 @Test(expected = MethodNotAllowedException.class)
 public void shouldThrowMethodNotAllowed() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/foo/foo23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   resolver.resolve(request);
 }
Пример #11
0
 @Test
 public void shouldResolveAliasCrudRouteForDelete() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.DELETE, "/blah/foo/foo23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   Action action = resolver.resolve(request);
   assertNotNull(action);
   assertEquals(HttpMethod.DELETE, action.getRoute().getMethod());
   assertEquals("/foo/{fooId}", action.getRoute().getPattern());
 }
Пример #12
0
 @Test
 public void shouldResolveAliasFooPostRoute() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.POST, "/yada/yada.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   Action action = resolver.resolve(request);
   assertNotNull(action);
   assertEquals(HttpMethod.POST, action.getRoute().getMethod());
   assertEquals("/foo", action.getRoute().getPattern());
 }
Пример #13
0
  @Override
  public void handle(ChannelHandlerContext ctx, FullHttpRequest request) {

    Tracker.getInstance().track(request);

    final String tenantId = request.headers().get("tenantId");

    HttpRequestWithDecodedQueryParams requestWithParams =
        (HttpRequestWithDecodedQueryParams) request;

    // get the query param
    List<String> query = requestWithParams.getQueryParams().get("query");
    if (query == null || query.size() != 1) {
      DefaultHandler.sendErrorResponse(
          ctx, request, "Invalid Query String", HttpResponseStatus.BAD_REQUEST);
      return;
    }

    // get the include_enum_values param to determine if results should contain enum values if
    // applicable
    List<String> includeEnumValues = requestWithParams.getQueryParams().get("include_enum_values");

    if ((includeEnumValues != null)
        && (includeEnumValues.size() != 0)
        && (includeEnumValues.get(0).compareToIgnoreCase("true") == 0)) {
      // include_enum_values is present and set to true, use the ENUMS_DISCOVERY_MODULES as the
      // discoveryHandle
      discoveryHandle =
          (DiscoveryIO)
              ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.ENUMS_DISCOVERY_MODULES);
    } else {
      // default discoveryHandle to DISCOVERY_MODULES
      discoveryHandle =
          (DiscoveryIO) ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES);
    }

    if (discoveryHandle == null) {
      sendResponse(ctx, request, null, HttpResponseStatus.NOT_FOUND);
      return;
    }

    try {
      List<SearchResult> searchResults = discoveryHandle.search(tenantId, query.get(0));
      sendResponse(ctx, request, getSerializedJSON(searchResults), HttpResponseStatus.OK);
    } catch (Exception e) {
      log.error(
          String.format("Exception occurred while trying to get metrics index for %s", tenantId),
          e);
      DefaultHandler.sendErrorResponse(
          ctx, request, "Error getting metrics index", HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
  }
 @Test
 public void clientRequestStreamDependencyInHttpMessageFlow() throws Exception {
   setServerLatch(2);
   final String text = "hello world big time data!";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final String text2 = "hello world big time data...number 2!!";
   final ByteBuf content2 = Unpooled.copiedBuffer(text2.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.PUT, "/some/path/resource", content, true);
   final FullHttpMessage request2 =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.PUT, "/some/path/resource2", content2, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     HttpHeaders httpHeaders2 = request2.headers();
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3);
     httpHeaders2.set(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 123);
     httpHeaders2.set(HttpHeaders.Names.CONTENT_LENGTH, text2.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("PUT")).path(as("/some/path/resource"));
     final Http2Headers http2Headers2 =
         new DefaultHttp2Headers().method(as("PUT")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeHeaders(ctxClient(), 5, http2Headers2, 0, false, newPromiseClient());
             frameWriter.writePriority(ctxClient(), 5, 3, (short) 123, true, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             frameWriter.writeData(ctxClient(), 5, content2.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> httpObjectCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener, times(2)).messageReceived(httpObjectCaptor.capture());
     capturedRequests = httpObjectCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
     assertEquals(request2, capturedRequests.get(1));
   } finally {
     request.release();
     request2.release();
   }
 }
Пример #15
0
 @Test
 public void shouldSendAllowedMethodsForGetRoute() {
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/foo/bar/bar23.json?value=ignored");
   httpRequest.headers().add("Host", "testing-host");
   Request request = new Request(httpRequest, null);
   try {
     resolver.resolve(request);
   } catch (MethodNotAllowedException e) {
     List<HttpMethod> allowed = e.getAllowedMethods();
     assertEquals(1, allowed.size());
     assertTrue(allowed.contains(HttpMethod.GET));
   }
 }
  protected FullHttpResponse newHandshakeResponse(FullHttpRequest var1, HttpHeaders var2) {
    DefaultFullHttpResponse var3 =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
    if (var2 != null) {
      var3.headers().add(var2);
    }

    String var4 = var1.headers().get("Sec-WebSocket-Key");
    if (var4 == null) {
      throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    } else {
      String var5 = var4 + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      byte[] var6 = WebSocketUtil.sha1(var5.getBytes(CharsetUtil.US_ASCII));
      String var7 = WebSocketUtil.base64(var6);
      if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 13 server handshake key: {}, response: {}", var4, var7);
      }

      var3.headers().add((String) "Upgrade", (Object) "WebSocket".toLowerCase());
      var3.headers().add((String) "Connection", (Object) "Upgrade");
      var3.headers().add((String) "Sec-WebSocket-Accept", (Object) var7);
      String var8 = var1.headers().get("Sec-WebSocket-Protocol");
      if (var8 != null) {
        String var9 = this.selectSubprotocol(var8);
        if (var9 == null) {
          if (logger.isDebugEnabled()) {
            logger.debug("Requested subprotocol(s) not supported: {}", (Object) var8);
          }
        } else {
          var3.headers().add((String) "Sec-WebSocket-Protocol", (Object) var9);
        }
      }

      return var3;
    }
  }
  /**
   * Handle the web socket handshake for the web socket specification <a href=
   * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi versions 13-17</a>.
   * Versions 13-17 share the same wire protocol.
   *
   * <p>Browser request to the server:
   *
   * <pre>
   * GET /chat HTTP/1.1
   * Host: server.example.com
   * Upgrade: websocket
   * Connection: Upgrade
   * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
   * Sec-WebSocket-Origin: http://example.com
   * Sec-WebSocket-Protocol: chat, superchat
   * Sec-WebSocket-Version: 13
   * </pre>
   *
   * <p>Server response:
   *
   * <pre>
   * HTTP/1.1 101 Switching Protocols
   * Upgrade: websocket
   * Connection: Upgrade
   * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
   * Sec-WebSocket-Protocol: chat
   * </pre>
   */
  @Override
  protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    FullHttpResponse res =
        new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
    if (headers != null) {
      res.headers().add(headers);
    }

    CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    if (key == null) {
      throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);

    if (logger.isDebugEnabled()) {
      logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
    }

    res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
    String subprotocols = req.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    if (subprotocols != null) {
      String selectedSubprotocol = selectSubprotocol(subprotocols);
      if (selectedSubprotocol == null) {
        if (logger.isDebugEnabled()) {
          logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
        }
      } else {
        res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
      }
    }
    return res;
  }
Пример #18
0
 /**
  * Method to easily create a request.
  *
  * @param httpMethod the {@link HttpMethod} desired.
  * @param uri string representation of the desired URI.
  * @param headers any associated headers as a {@link HttpHeaders} object. Can be null.
  * @param content the content that accompanies the request. Can be null.
  * @return A {@link FullHttpRequest} object that defines the request required by the input.
  */
 private FullHttpRequest buildRequest(
     HttpMethod httpMethod, String uri, HttpHeaders headers, ByteBuffer content) {
   ByteBuf contentBuf;
   if (content != null) {
     contentBuf = Unpooled.wrappedBuffer(content);
   } else {
     contentBuf = Unpooled.buffer(0);
   }
   FullHttpRequest httpRequest =
       new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, contentBuf);
   if (headers != null) {
     httpRequest.headers().set(headers);
   }
   return httpRequest;
 }
Пример #19
0
 @Override
 public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise)
     throws Exception {
   if (msg instanceof ByteBuf) {
     ByteBuf buf = (ByteBuf) msg;
     FullHttpRequest httpRequest =
         new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "", buf);
     httpRequest
         .headers()
         .add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
     ctx.write(httpRequest, promise);
   } else {
     ctx.write(msg, promise);
   }
 }
 @Test
 public void clientRequestMultipleHeaders() throws Exception {
   // writeHeaders will implicitly add an END_HEADERS tag each time and so this test does not
   // follow the HTTP
   // message flow. We currently accept this message flow and just add the second headers to the
   // trailing headers.
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     HttpHeaders trailingHeaders = request.trailingHeaders();
     trailingHeaders.set("FoO", "goo");
     trailingHeaders.set("foO2", "goo2");
     trailingHeaders.add("fOo2", "goo3");
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     final Http2Headers http2Headers2 =
         new DefaultHttp2Headers()
             .set(as("foo"), as("goo"))
             .set(as("foo2"), as("goo2"))
             .add(as("foo2"), as("goo3"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers2, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
Пример #21
0
  private FullHttpRequest convertToHttpRequest(Invocation invocation) {
    requireNonNull(invocation, "invocation");
    final ServiceInvocationContext ctx = invocation.invocationContext();
    final FullHttpRequest request;
    final Object content = invocation.content();

    if (content instanceof FullHttpRequest) {
      request = (FullHttpRequest) content;
    } else if (content instanceof ByteBuf) {
      request =
          new DefaultFullHttpRequest(
              HttpVersion.HTTP_1_1, HttpMethod.POST, ctx.path(), (ByteBuf) content);
    } else {
      throw new IllegalStateException(
          "content is not a ByteBuf or FullHttpRequest: " + content.getClass().getName());
    }

    HttpHeaders headers = request.headers();

    headers.set(HttpHeaderNames.HOST, ctx.host());
    headers.set(ExtensionHeaderNames.SCHEME.text(), sessionProtocol.uriText());
    headers.set(HttpHeaderNames.USER_AGENT, ARMERIA_USER_AGENT);
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    ByteBuf contentBuf = request.content();
    if (contentBuf != null && contentBuf.isReadable()) {
      headers.set(HttpHeaderNames.CONTENT_LENGTH, contentBuf.readableBytes());
    }

    invocation.options().get(ClientOption.HTTP_HEADERS).ifPresent(headers::add);
    if (ctx.scheme().serializationFormat() != SerializationFormat.NONE) {
      // we allow a user can set content type and accept headers
      String mimeType = ctx.scheme().serializationFormat().mimeType();
      if (!headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, mimeType);
      }
      if (!headers.contains(HttpHeaderNames.ACCEPT)) {
        headers.set(HttpHeaderNames.ACCEPT, mimeType);
      }
    }

    return request;
  }
Пример #22
0
  private void processHead(ChannelHandlerContext context, FullHttpRequest request) {
    HttpHeaders headers = request.headers();
    FullHttpResponse response = null;

    if (headers.contains(Names.CONTENT_LENGTH)) {

      try {
        File file = getRequestedFile(request.getUri());

        response =
            new DefaultFullHttpResponse(
                HTTP_1_1, request.getDecoderResult().isSuccess() ? OK : BAD_REQUEST);

        HttpHeaders.setContentLength(response, file.length());

      } catch (FileNotFoundException | URISyntaxException e) {
        response = getBadRequest(e.getMessage());
      }
    }

    context.writeAndFlush(response);
  }
Пример #23
0
  /** Write the response */
  private void writeResponse(ChannelHandlerContext ctx) {
    // Convert the response content to a ByteBuf.
    ByteBuf buf = Unpooled.copiedBuffer(responseContent.toString(), WaarpStringUtils.UTF8);
    responseContent.setLength(0);

    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    boolean close =
        HttpHeaderValues.CLOSE.contentEqualsIgnoreCase(
                request.headers().get(HttpHeaderNames.CONNECTION))
            || (!keepAlive)
            || forceClose;

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
    if (keepAlive) {
      response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    if (!close) {
      // There's no need to add 'Content-Length' header
      // if this is the last response.
      response.headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
    }

    handleCookies(response);

    // Write the response.
    ChannelFuture future = ctx.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
      future.addListener(WaarpSslUtility.SSLCLOSE);
    }
    if (shutdown) {
      ChannelUtils.startShutdown();
    }
  }
Пример #24
0
 @Override
 protected void encode(ChannelHandlerContext ctx, HttpXmlRequest msg, List<Object> out)
     throws Exception {
   ByteBuf body = encode0(ctx, msg.getBody());
   FullHttpRequest request = msg.getRequest();
   if (request == null) {
     request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/do", body);
     HttpHeaders headers = request.headers();
     headers.set(HttpHeaders.Names.HOST, InetAddress.getLocalHost().getHostAddress());
     headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
     headers.set(
         HttpHeaders.Names.ACCEPT_ENCODING,
         HttpHeaders.Values.GZIP.toString() + ',' + HttpHeaders.Values.DEFLATE.toString());
     headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
     headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "zh");
     headers.set(HttpHeaders.Names.USER_AGENT, "Netty xml Http Client side");
     headers.set(
         HttpHeaders.Names.ACCEPT,
         "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
   }
   HttpHeaders.setContentLength(request, body.readableBytes());
   out.add(request);
 }
  private boolean authenticate(FullHttpRequest request, InetSocketAddress remoteAddr) {
    String authToken = request.headers().get(HttpHeaderNames.AUTHORIZATION);
    if (authToken == null) {
      return false;
    }

    AgentKey key = null;

    try {
      key = AgentKey.load(authToken);
    } catch (SQLException e) {
      l.error("Error loading agent key:", e);
      return false;
    }

    if (key == null) return false;

    if (key.Expiration != null && key.Expiration.getTime() <= System.currentTimeMillis())
      return false;

    if (key.IPRange != null) {
      if (ValidAddrs == null || !ValidAddrs.getAddrString().equals(key.IPRange)) {
        try {
          ValidAddrs = new SubnetMask(key.IPRange);
        } catch (Exception e) {
          // Should not happen
          l.error("Invalid IPRange in agent key " + authToken + " " + key.IPRange, e);
          return false;
        }
      }

      if (!ValidAddrs.match(remoteAddr.getAddress())) return false;
    }

    return true;
  }
  private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {

    if (!req.getDecoderResult().isSuccess()
        || (!"websocket".equals(req.headers().get("Upgrade")))) {

      sendHttpResponse(
          ctx,
          req,
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));

      return;
    }

    WebSocketServerHandshakerFactory wsFactory =
        new WebSocketServerHandshakerFactory("ws://localhost:7397/websocket", null, false);

    handshaker = wsFactory.newHandshaker(req);

    if (handshaker == null) {
      WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
      handshaker.handshake(ctx.channel(), req);
    }
  }
 @Test
 public void clientRequestSingleHeaderNoDataFrames() throws Exception {
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "https");
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "example.org");
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, 0);
     final Http2Headers http2Headers =
         new DefaultHttp2Headers()
             .method(as("GET"))
             .scheme(as("https"))
             .authority(as("example.org"))
             .path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
 private static String getWebSocketLocation(FullHttpRequest req) {
   return "ws://" + req.headers().get(Names.HOST);
 }
  private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    // Handle a bad request.
    if (!request.getDecoderResult().isSuccess()) {
      sendHttpResponse(
          ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
      return;
    }

    if (RouterHits.checkIfMappingExit(request)) {
      // Do Router Mapping First
      RouterHits.execute(ctx, request);
      return;
    }

    if ("/websocket".equals(request.getUri())) {
      // Handshake
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(getWebSocketLocation(request), null, true);
      handshaker = wsFactory.newHandshaker(request);
      if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
      } else {
        handshaker.handshake(ctx.channel(), request);
        channels.add(ctx.channel());
      }
      return;
    }

    final String uri = request.getUri();
    // System.out.println("uri: " + uri);
    final String path = sanitizeUri("www", uri);
    // System.out.println("path: " + path);
    if (path == null) {
      sendHttpResponse(
          ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));

      return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
      sendHttpResponse(
          ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
      return;
    }

    if (file.isDirectory()) {
      if (uri.endsWith("/")) {

        File checkIndexFile = new File(file.getAbsolutePath() + File.separator + "index.html");

        System.out.println(checkIndexFile.exists());
        if (checkIndexFile.exists()) {
          file = checkIndexFile;
        } else {
          sendListing(ctx, file);
          return;
        }
      } else {
        sendRedirect(ctx, uri + '/');
      }
    }

    if (!file.isFile()) {
      sendHttpResponse(
          ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
      return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
      SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
      Date ifModifiedSinceDate = null;
      try {
        ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      // Only compare up to the second because the datetime format we send to the client
      // does not have milliseconds
      long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
      long fileLastModifiedSeconds = file.lastModified() / 1000;
      if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
        sendNotModified(ctx);
        return;
      }
    }

    RandomAccessFile raf;
    try {
      raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
      sendHttpResponse(
          ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
      return;
    }
    long fileLength = 0;
    try {
      fileLength = raf.length();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
      response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture = null;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
      sendFileFuture =
          ctx.write(
              new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
      // Write the end marker.
      lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
      try {
        sendFileFuture =
            ctx.writeAndFlush(
                new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      // HttpChunkedInput will write the end marker (LastHttpContent) for us.
      lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(
        new ChannelProgressiveFutureListener() {
          @Override
          public void operationProgressed(
              ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
              System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
              System.err.println(
                  future.channel() + " Transfer progress: " + progress + " / " + total);
            }
          }

          @Override
          public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
          }
        });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
      // Close the connection when the whole content is written out.
      lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

    //        // Send the demo page and favicon.ico
    //        if ("/".equals(req.getUri()) && req.getMethod() == GET) {
    //            ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    //
    //            res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    //            HttpHeaders.setContentLength(res, content.readableBytes());
    //
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }
    //
    //        if ("/favicon.ico".equals(req.getUri())) {
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }

    sendHttpResponse(
        ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    return;
  }
Пример #30
0
  public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest)
      throws Exception {
    if (!nettyRequest.getDecoderResult().isSuccess()) {
      sendError(ctx, HttpResponseStatus.BAD_REQUEST);
      return;
    }

    final long startTime = System.nanoTime();

    final Request request =
        new DefaultRequest(
            new NettyHeadersBackedHeaders(nettyRequest.headers()),
            nettyRequest.getMethod().name(),
            nettyRequest.getUri(),
            nettyRequest.content());

    final Channel channel = ctx.channel();

    final DefaultMutableStatus responseStatus = new DefaultMutableStatus();
    final HttpHeaders httpHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders);
    FileHttpTransmitter fileHttpTransmitter =
        new DefaultFileHttpTransmitter(
            nettyRequest,
            httpHeaders,
            channel,
            compressResponses,
            addResponseTimeHeader ? startTime : -1);

    final DefaultEventController<RequestOutcome> requestOutcomeEventController =
        new DefaultEventController<>();

    // We own the lifecycle
    nettyRequest.content().retain();

    final Response response =
        new DefaultResponse(
            responseStatus,
            responseHeaders,
            fileHttpTransmitter,
            ctx.alloc(),
            new Action<ByteBuf>() {
              @Override
              public void execute(final ByteBuf byteBuf) throws Exception {
                final HttpResponse nettyResponse =
                    new CustomHttpResponse(responseStatus.getResponseStatus(), httpHeaders);

                nettyRequest.content().release();
                responseHeaders.set(HttpHeaderConstants.CONTENT_LENGTH, byteBuf.writerIndex());
                boolean shouldClose = true;
                if (channel.isOpen()) {
                  if (isKeepAlive(nettyRequest)) {
                    responseHeaders.set(
                        HttpHeaderConstants.CONNECTION, HttpHeaderConstants.KEEP_ALIVE);
                    shouldClose = false;
                  }

                  long stopTime = System.nanoTime();
                  if (addResponseTimeHeader) {
                    responseHeaders.set(
                        "X-Response-Time", NumberUtil.toMillisDiffString(startTime, stopTime));
                  }

                  execController.getExecution().complete();

                  channel.writeAndFlush(nettyResponse);
                  channel.write(new DefaultHttpContent(byteBuf));
                  ChannelFuture future = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

                  if (requestOutcomeEventController.isHasListeners()) {
                    Headers headers = new DelegatingHeaders(responseHeaders);
                    Status status =
                        new DefaultStatus(responseStatus.getCode(), responseStatus.getMessage());
                    SentResponse sentResponse = new DefaultSentResponse(headers, status);
                    RequestOutcome requestOutcome =
                        new DefaultRequestOutcome(
                            request, sentResponse, System.currentTimeMillis());
                    requestOutcomeEventController.fire(requestOutcome);
                  }
                  if (shouldClose) {
                    future.addListener(ChannelFutureListener.CLOSE);
                  }
                }
              }
            });

    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress);

    Action<Action<Object>> subscribeHandler =
        new Action<Action<Object>>() {
          @Override
          public void execute(Action<Object> thing) throws Exception {
            channelSubscriptions.put(channel, thing);
            channel
                .closeFuture()
                .addListener(
                    new ChannelFutureListener() {
                      @Override
                      public void operationComplete(ChannelFuture future) throws Exception {
                        channelSubscriptions.remove(channel);
                      }
                    });
          }
        };

    final DirectChannelAccess directChannelAccess =
        new DefaultDirectChannelAccess(channel, subscribeHandler);

    execController.start(
        new Action<Execution>() {
          @Override
          public void execute(Execution execution) throws Exception {
            DefaultContext.RequestConstants requestConstants =
                new DefaultContext.RequestConstants(
                    applicationConstants,
                    bindAddress,
                    request,
                    response,
                    directChannelAccess,
                    requestOutcomeEventController.getRegistry(),
                    execution);

            new DefaultContext(requestConstants, registry, handlers, 0, return404).next();
          }
        });
  }