@Test
  public void testCase() throws Exception {
    HttpFields fields = new HttpFields();
    Set s;
    //         0123456789012345678901234567890
    byte[] b = "Message-IDmessage-idvalueVALUE".getBytes();
    ByteArrayBuffer buf = new ByteArrayBuffer(512);
    buf.put(b);

    View headUC = new View.CaseInsensitive(buf);
    View headLC = new View.CaseInsensitive(buf);
    View valUC = new View(buf);
    View valLC = new View(buf);
    headUC.update(0, 10);
    headLC.update(10, 20);
    valUC.update(20, 25);
    valLC.update(25, 30);

    fields.add("header", "value");
    fields.add(headUC, valLC);
    fields.add("other", "data");
    s = enum2set(fields.getFieldNames());
    assertEquals(3, s.size());
    assertTrue(s.contains("message-id"));
    assertEquals("value", fields.getStringField("message-id").toLowerCase());
    assertEquals("value", fields.getStringField("Message-ID").toLowerCase());

    fields.clear();

    fields.add("header", "value");
    fields.add(headLC, valLC);
    fields.add("other", "data");
    s = enum2set(fields.getFieldNames());
    assertEquals(3, s.size());
    assertTrue(s.contains("message-id"));
    assertEquals("value", fields.getStringField("Message-ID").toLowerCase());
    assertEquals("value", fields.getStringField("message-id").toLowerCase());

    fields.clear();

    fields.add("header", "value");
    fields.add(headUC, valUC);
    fields.add("other", "data");
    s = enum2set(fields.getFieldNames());
    assertEquals(3, s.size());
    assertTrue(s.contains("message-id"));
    assertEquals("value", fields.getStringField("message-id").toLowerCase());
    assertEquals("value", fields.getStringField("Message-ID").toLowerCase());

    fields.clear();

    fields.add("header", "value");
    fields.add(headLC, valUC);
    fields.add("other", "data");
    s = enum2set(fields.getFieldNames());
    assertEquals(3, s.size());
    assertTrue(s.contains("message-id"));
    assertEquals("value", fields.getStringField("Message-ID").toLowerCase());
    assertEquals("value", fields.getStringField("message-id").toLowerCase());
  }
Beispiel #2
0
  /**
   * Makes sure that the response contains an unfiltered file contents.
   *
   * <p>This is used to test exclusions and passthroughs in the GzipFilter.
   *
   * <p>An example is to test that it is possible to configure GzipFilter to not recompress content
   * that shouldn't be compressed by the GzipFilter.
   *
   * @param requestedFilename the filename used to on the GET request,.
   * @param testResourceSha1Sum the sha1sum file that contains the SHA1SUM checksum that will be
   *     used to verify that the response contents are what is intended.
   * @param expectedContentType
   */
  public void assertIsResponseNotGzipFiltered(
      String requestedFilename, String testResourceSha1Sum, String expectedContentType)
      throws Exception {
    System.err.printf("[GzipTester] requesting /context/%s%n", requestedFilename);
    HttpTester request = new HttpTester();
    HttpTester response = new HttpTester();

    request.setMethod("GET");
    request.setVersion("HTTP/1.0");
    request.setHeader("Host", "tester");
    request.setHeader("Accept-Encoding", compressionType);
    if (this.userAgent != null) request.setHeader("User-Agent", this.userAgent);
    request.setURI("/context/" + requestedFilename);

    // Issue the request
    ByteArrayBuffer reqsBuff = new ByteArrayBuffer(request.generate().getBytes());
    // Collect the response(s)
    ByteArrayBuffer respBuff = servletTester.getResponses(reqsBuff);
    response.parse(respBuff.asArray());

    dumpHeaders(requestedFilename + " / Response Headers", response);

    // Assert the response headers
    String prefix = requestedFilename + " / Response";
    Assert.assertThat(prefix + ".method", response.getMethod(), nullValue());
    Assert.assertThat(prefix + ".status", response.getStatus(), is(HttpServletResponse.SC_OK));
    Assert.assertThat(
        prefix + ".header[Content-Length]", response.getHeader("Content-Length"), notNullValue());
    Assert.assertThat(
        prefix + ".header[Content-Encoding] (should not be recompressed by GzipFilter)",
        response.getHeader("Content-Encoding"),
        nullValue());
    Assert.assertThat(
        prefix + ".header[Content-Type] (should have a Content-Type associated with it)",
        response.getHeader("Content-Type"),
        notNullValue());
    Assert.assertThat(
        prefix + ".header[Content-Type]",
        response.getHeader("Content-Type"),
        is(expectedContentType));

    ByteArrayInputStream bais = null;
    DigestOutputStream digester = null;
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA1");
      bais = new ByteArrayInputStream(response.getContentBytes());
      digester = new DigestOutputStream(new NoOpOutputStream(), digest);
      IO.copy(bais, digester);

      String actualSha1Sum = Hex.asHex(digest.digest());
      String expectedSha1Sum = loadExpectedSha1Sum(testResourceSha1Sum);
      Assert.assertEquals(
          requestedFilename + " / SHA1Sum of content", expectedSha1Sum, actualSha1Sum);
    } finally {
      IO.close(digester);
      IO.close(bais);
    }
  }
 /* ------------------------------------------------------------ */
 private void doTheHixieHixieShake() {
   byte[] result =
       WebSocketConnectionD00.doTheHixieHixieShake(
           WebSocketConnectionD00.hixieCrypt(_key1),
           WebSocketConnectionD00.hixieCrypt(_key2),
           _hixieBytes.asArray());
   _hixieBytes.clear();
   _hixieBytes.put(result);
 }
Beispiel #4
0
  public void assertIsResponseGzipCompressed(String requestedFilename, String serverFilename)
      throws Exception {
    System.err.printf("[GzipTester] requesting /context/%s%n", requestedFilename);
    HttpTester request = new HttpTester();
    HttpTester response = new HttpTester();

    request.setMethod("GET");
    request.setVersion("HTTP/1.0");
    request.setHeader("Host", "tester");
    request.setHeader("Accept-Encoding", compressionType);
    if (this.userAgent != null) request.setHeader("User-Agent", this.userAgent);
    request.setURI("/context/" + requestedFilename);

    // Issue the request
    ByteArrayBuffer reqsBuff = new ByteArrayBuffer(request.generate().getBytes());
    // Collect the response(s)
    ByteArrayBuffer respBuff = servletTester.getResponses(reqsBuff);
    response.parse(respBuff.asArray());

    // Assert the response headers
    Assert.assertThat("Response.method", response.getMethod(), nullValue());
    //
    // Assert.assertThat("Response.status",response.getStatus(),is(HttpServletResponse.SC_OK));
    Assert.assertThat(
        "Response.header[Content-Length]", response.getHeader("Content-Length"), notNullValue());
    Assert.assertThat(
        "Response.header[Content-Encoding]",
        response.getHeader("Content-Encoding"),
        containsString(compressionType));

    // Assert that the decompressed contents are what we expect.
    File serverFile = testdir.getFile(serverFilename);
    String expected = IO.readToString(serverFile);
    String actual = null;

    ByteArrayInputStream bais = null;
    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
      bais = new ByteArrayInputStream(response.getContentBytes());
      if (compressionType.equals(GzipFilter.GZIP)) {
        in = new GZIPInputStream(bais);
      } else if (compressionType.equals(GzipFilter.DEFLATE)) {
        in = new InflaterInputStream(bais, new Inflater(true));
      }
      out = new ByteArrayOutputStream();
      IO.copy(in, out);

      actual = out.toString(encoding);
      assertThat("Uncompressed contents", actual, equalTo(expected));
    } finally {
      IO.close(out);
      IO.close(in);
      IO.close(bais);
    }
  }
  @Test
  public void testCRLF() throws Exception {
    HttpFields header = new HttpFields();

    header.put("name0", "value\r\n0");
    header.put("name\r\n1", "value1");
    header.put("name:2", "value:\r\n2");

    ByteArrayBuffer buffer = new ByteArrayBuffer(1024);
    header.putTo(buffer);
    assertTrue(buffer.toString().contains("name0: value0"));
    assertTrue(buffer.toString().contains("name1: value1"));
    assertTrue(buffer.toString().contains("name2: value:2"));
  }
Beispiel #6
0
  public void sendMessage(String... msgs) throws IOException {
    int len = 0;
    for (String msg : msgs) {
      LOG.debug("sending message: " + msg);
      len += (msg.length() + 2);
    }

    ByteArrayBuffer buf = new ByteArrayBuffer(len);

    for (String msg : msgs) {
      buf.put((byte) 0x00);
      buf.put(msg.getBytes("UTF-8"));
      buf.put((byte) 0xFF);
    }

    out.write(buf.array());
    out.flush();
  }
Beispiel #7
0
  private HttpTester executeRequest(String uri) throws IOException, Exception {
    System.err.printf("[GzipTester] requesting %s%n", uri);
    HttpTester request = new HttpTester();
    HttpTester response = new HttpTester();

    request.setMethod("GET");
    request.setVersion("HTTP/1.0");
    request.setHeader("Host", "tester");
    request.setHeader("Accept-Encoding", compressionType);
    if (this.userAgent != null) request.setHeader("User-Agent", this.userAgent);

    request.setURI(uri);

    // Issue the request
    ByteArrayBuffer reqsBuff = new ByteArrayBuffer(request.generate().getBytes());
    // Collect the response(s)
    ByteArrayBuffer respBuff = servletTester.getResponses(reqsBuff);
    response.parse(respBuff.asArray());
    return response;
  }
  /* (non-Javadoc)
   * @see org.eclipse.jetty.websocket.AbstractExtension#onFrame(byte, byte, org.eclipse.jetty.io.Buffer)
   */
  @Override
  public void onFrame(byte flags, byte opcode, Buffer buffer) {
    if (getConnection().isControl(opcode) || !isFlag(flags, 1)) {
      super.onFrame(flags, opcode, buffer);
      return;
    }

    if (buffer.array() == null) buffer = buffer.asMutableBuffer();

    int length = 0xff & buffer.get();
    if (length >= 0x7e) {
      int b = (length == 0x7f) ? 8 : 2;
      length = 0;
      while (b-- > 0) length = 0x100 * length + (0xff & buffer.get());
    }

    // TODO check a max framesize

    _inflater.setInput(buffer.array(), buffer.getIndex(), buffer.length());
    ByteArrayBuffer buf = new ByteArrayBuffer(length);
    try {
      while (_inflater.getRemaining() > 0) {
        int inflated = _inflater.inflate(buf.array(), buf.putIndex(), buf.space());
        if (inflated == 0) throw new DataFormatException("insufficient data");
        buf.setPutIndex(buf.putIndex() + inflated);
      }

      super.onFrame(clearFlag(flags, 1), opcode, buf);
    } catch (DataFormatException e) {
      LOG.warn(e);
      getConnection().close(WebSocketConnectionRFC6455.CLOSE_BAD_PAYLOAD, e.toString());
    }
  }
  /* ------------------------------------------------------------ */
  public Connection handle() throws IOException {
    try {
      // handle stupid hixie random bytes
      if (_hixieBytes != null) {

        // take any available bytes from the parser buffer, which may have already been read
        Buffer buffer = _parser.getBuffer();
        if (buffer != null && buffer.length() > 0) {
          int l = buffer.length();
          if (l > (8 - _hixieBytes.length())) l = 8 - _hixieBytes.length();
          _hixieBytes.put(buffer.peek(buffer.getIndex(), l));
          buffer.skip(l);
        }

        // while we are not blocked
        while (_endp.isOpen()) {
          // do we now have enough
          if (_hixieBytes.length() == 8) {
            // we have the silly random bytes
            // so let's work out the stupid 16 byte reply.
            doTheHixieHixieShake();
            _endp.flush(_hixieBytes);
            _hixieBytes = null;
            _endp.flush();
            break;
          }

          // no, then let's fill
          int filled = _endp.fill(_hixieBytes);
          if (filled < 0) {
            _endp.flush();
            _endp.close();
            break;
          }
        }

        if (_websocket instanceof OnFrame) ((OnFrame) _websocket).onHandshake(this);
        _websocket.onOpen(this);
        return this;
      }

      // handle the framing protocol
      boolean progress = true;

      while (progress) {
        int flushed = _generator.flush();
        int filled = _parser.parseNext();

        progress = flushed > 0 || filled > 0;

        _endp.flush();

        if (_endp instanceof AsyncEndPoint && ((AsyncEndPoint) _endp).hasProgressed())
          progress = true;
      }
    } catch (IOException e) {
      LOG.debug(e);
      try {
        if (_endp.isOpen()) _endp.close();
      } catch (IOException e2) {
        LOG.ignore(e2);
      }
      throw e;
    } finally {
      if (_endp.isOpen()) {
        if (_endp.isInputShutdown() && _generator.isBufferEmpty()) _endp.close();
        else checkWriteable();

        checkWriteable();
      }
    }
    return this;
  }