Ejemplo n.º 1
1
  static void toHexString(String header, ByteBuffer buf) {
    sb.delete(0, sb.length());

    for (int index = 0; index < buf.limit(); index++) {
      String hex = Integer.toHexString(0x0100 + (buf.get(index) & 0x00FF)).substring(1);
      sb.append((hex.length() < 2 ? "0" : "") + hex + " ");
    }
    LOG.debug(
        "hex->"
            + header
            + ": position,limit,capacity "
            + buf.position()
            + ","
            + buf.limit()
            + ","
            + buf.capacity());
    LOG.debug("hex->" + sb.toString());
  }
Ejemplo n.º 2
0
  /*
   * Creates a file at filename if file doesn't exist. Writes
   * value to that file using FileChannel.
   */
  public static void writeToFile(File filename, String value, String hideCommand)
      throws IOException, InterruptedException {
    if (!hideCommand.trim().equals("")) {
      // unhideFile(filename);
    }

    if (!filename.exists()) {
      filename.createNewFile();
    }

    byte[] bytes = value.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    for (int i = 0; i < bytes.length; i++) {
      buffer.put(bytes[i]);
    }
    buffer.rewind();

    try {

      fileWriter = new FileOutputStream(filename).getChannel();
      fileWriter.write(buffer);
    } finally {
      fileWriter.close();
    }

    if (!hideCommand.trim().equals("")) {
      // hideFile(filename);
    }
  }
Ejemplo n.º 3
0
  public static void main(String[] argv) throws Exception {
    Pipe[] pipes = new Pipe[PIPES_COUNT];
    Pipe pipe = Pipe.open();
    Pipe.SinkChannel sink = pipe.sink();
    Pipe.SourceChannel source = pipe.source();
    Selector sel = Selector.open();
    source.configureBlocking(false);
    source.register(sel, SelectionKey.OP_READ);

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i] = Pipe.open();
      Pipe.SourceChannel sc = pipes[i].source();
      sc.configureBlocking(false);
      sc.register(sel, SelectionKey.OP_READ);
      Pipe.SinkChannel sc2 = pipes[i].sink();
      sc2.configureBlocking(false);
      sc2.register(sel, SelectionKey.OP_WRITE);
    }

    for (int i = 0; i < LOOPS; i++) {
      sink.write(ByteBuffer.allocate(BUF_SIZE));
      int x = sel.selectNow();
      sel.selectedKeys().clear();
      source.read(ByteBuffer.allocate(BUF_SIZE));
    }

    for (int i = 0; i < PIPES_COUNT; i++) {
      pipes[i].sink().close();
      pipes[i].source().close();
    }
    pipe.sink().close();
    pipe.source().close();
    sel.close();
  }
Ejemplo n.º 4
0
  private static void scScatter() throws Exception {
    Pipe p = Pipe.open();
    Pipe.SinkChannel sink = p.sink();
    Pipe.SourceChannel source = p.source();
    sink.configureBlocking(false);

    ByteBuffer outgoingdata = ByteBuffer.allocateDirect(30);
    byte[] someBytes = new byte[30];
    generator.nextBytes(someBytes);
    outgoingdata.put(someBytes);
    outgoingdata.flip();

    int totalWritten = 0;
    while (totalWritten < 30) {
      int written = sink.write(outgoingdata);
      if (written < 0) throw new Exception("Write failed");
      totalWritten += written;
    }

    ByteBuffer[] bufs = new ByteBuffer[3];
    for (int i = 0; i < 3; i++) bufs[i] = ByteBuffer.allocateDirect(10);
    long numBytesRead = source.read(bufs);
    if (numBytesRead < 30) throw new Exception("Pipe test failed");
    sink.close();
    source.close();
  }
Ejemplo n.º 5
0
  // Test the connected case to see if PUE is thrown
  public static void test2() throws Exception {

    setup();
    server.configureBlocking(true);
    server.connect(isa);
    server.configureBlocking(false);
    outBuf.rewind();
    server.write(outBuf);
    server.receive(inBuf);

    client.close();
    Thread.sleep(2000);
    outBuf.rewind();

    try {
      server.write(outBuf);
      Thread.sleep(2000);
      inBuf.clear();
      server.read(inBuf);
      if (onSolarisOrLinux()) throw new Exception("Expected PUE not thrown");
    } catch (PortUnreachableException pue) {
      System.err.println("received PUE");
    }
    server.close();
  }
Ejemplo n.º 6
0
  /*
   * Begin the shutdown process.
   * <P>
   * Close out the SSLEngine if not already done so, then
   * wrap our outgoing close_notify message and try to send it on.
   * <P>
   * Return true when we're done passing the shutdown messsages.
   */
  boolean shutdown() throws IOException {

    if (!shutdown) {
      sslEngine.closeOutbound();
      shutdown = true;
    }

    if (outNetBB.hasRemaining() && tryFlush(outNetBB)) {
      return false;
    }

    /*
     * By RFC 2616, we can "fire and forget" our close_notify
     * message, so that's what we'll do here.
     */
    outNetBB.clear();
    SSLEngineResult result = sslEngine.wrap(hsBB, outNetBB);
    if (result.getStatus() != Status.CLOSED) {
      throw new SSLException("Improper close state");
    }
    outNetBB.flip();

    /*
     * We won't wait for a select here, but if this doesn't work,
     * we'll cycle back through on the next select.
     */
    if (outNetBB.hasRemaining()) {
      tryFlush(outNetBB);
    }

    return (!outNetBB.hasRemaining() && (result.getHandshakeStatus() != HandshakeStatus.NEED_WRAP));
  }
Ejemplo n.º 7
0
 void send(byte[] data) throws IOException {
   SocketChannel channel = (SocketChannel) key.channel();
   verboseLog("TCP write", data);
   byte[] lengthArray = new byte[2];
   lengthArray[0] = (byte) (data.length >>> 8);
   lengthArray[1] = (byte) (data.length & 0xFF);
   ByteBuffer[] buffers = new ByteBuffer[2];
   buffers[0] = ByteBuffer.wrap(lengthArray);
   buffers[1] = ByteBuffer.wrap(data);
   int nsent = 0;
   key.interestOps(SelectionKey.OP_WRITE);
   try {
     while (nsent < data.length + 2) {
       if (key.isWritable()) {
         long n = channel.write(buffers);
         if (n < 0) throw new EOFException();
         nsent += (int) n;
         if (nsent < data.length + 2 && System.currentTimeMillis() > endTime)
           throw new SocketTimeoutException();
       } else blockUntil(key, endTime);
     }
   } finally {
     if (key.isValid()) key.interestOps(0);
   }
 }
Ejemplo n.º 8
0
  // Check if the datagramsocket adaptor can send with a packet
  // that has not been initialized with an address; the legacy
  // datagram socket will send in this case
  private static void test2() throws Exception {
    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    byte b[] = "hello".getBytes("UTF-8");
    DatagramPacket pkt = new DatagramPacket(b, b.length);
    sndChannel.socket().send(pkt);

    ByteBuffer bb = ByteBuffer.allocate(256);
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    // Check that the pkt got set with the target address;
    // This is legacy behavior
    if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Ejemplo n.º 9
0
 static byte[] extractByteArray(ByteBuffer buf) {
   int len = buf.getInt();
   if (len > 0) {
     byte[] a = new byte[len];
     buf.get(a, 0, len);
     return a;
   } else return new byte[0];
 }
Ejemplo n.º 10
0
  private boolean tagExists(FileChannel fc) throws IOException {
    ByteBuffer b = ByteBuffer.allocate(3);
    fc.position(0);
    fc.read(b);
    String tagString = new String(b.array());

    return tagString.equals("ID3");
  }
Ejemplo n.º 11
0
 LockAndModify(ByteBuffer mbb, int start, int end) {
   this.start = start;
   this.end = end;
   mbb.limit(end);
   mbb.position(start);
   buff = mbb.slice();
   start();
 }
Ejemplo n.º 12
0
 static void printBBInfo(ByteBuffer buf) {
   LOG.debug(
       "Info : position,limit,capacity "
           + buf.position()
           + ","
           + buf.limit()
           + ","
           + buf.capacity());
 }
Ejemplo n.º 13
0
 static void insertString(String str, ByteBuffer buf) throws java.io.UnsupportedEncodingException {
   if (str != null && str.length() > 0) {
     buf.putInt(str.length() + 1);
     buf.put(str.getBytes("UTF-8"), 0, str.length());
     buf.put((byte) 0);
   } else { // buffer is null or length 0
     buf.putInt(0);
   }
 }
Ejemplo n.º 14
0
 static void insertByteString(byte[] array, ByteBuffer buf)
     throws java.io.UnsupportedEncodingException {
   if (array != null && array.length > 0) {
     buf.putInt(array.length);
     buf.put(array, 0, array.length);
     buf.put((byte) 0);
   } else { // buffer is null or length 0
     buf.putInt(0);
   }
 }
Ejemplo n.º 15
0
 static byte[] extractByteString(ByteBuffer buf) {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len];
     buf.get(str, 0, len);
     buf.get(); // trailing null
   } else str = new byte[0];
   return str;
 }
Ejemplo n.º 16
0
 static String extractString(ByteBuffer buf) throws java.io.UnsupportedEncodingException {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len - 1];
     ;
     buf.get(str, 0, len - 1);
     buf.get(); // trailing null
   } else str = new byte[0];
   return new String(str, "UTF-8");
 }
Ejemplo n.º 17
0
  /*
   * Flush any remaining data.
   * <P>
   * Return true when the fileChannelBB and outNetBB are empty.
   */
  boolean dataFlush() throws IOException {
    boolean fileFlushed = true;

    if ((fileChannelBB != null) && fileChannelBB.hasRemaining()) {
      doWrite(fileChannelBB);
      fileFlushed = !fileChannelBB.hasRemaining();
    } else if (outNetBB.hasRemaining()) {
      tryFlush(outNetBB);
    }

    return (fileFlushed && !outNetBB.hasRemaining());
  }
Ejemplo n.º 18
0
  /*
   * Read the channel for more information, then unwrap the
   * (hopefully application) data we get.
   * <P>
   * If we run out of data, we'll return to our caller (possibly using
   * a Selector) to get notification that more is available.
   * <P>
   * Each call to this method will perform at most one underlying read().
   */
  int read() throws IOException {
    SSLEngineResult result;

    if (!initialHSComplete) {
      throw new IllegalStateException();
    }

    int pos = requestBB.position();

    if (sc.read(inNetBB) == -1) {
      sslEngine.closeInbound(); // probably throws exception
      return -1;
    }

    do {
      resizeRequestBB(); // expected room for unwrap
      inNetBB.flip();
      result = sslEngine.unwrap(inNetBB, requestBB);
      inNetBB.compact();

      /*
       * Could check here for a renegotation, but we're only
       * doing a simple read/write, and won't have enough state
       * transitions to do a complete handshake, so ignore that
       * possibility.
       */
      switch (result.getStatus()) {
        case BUFFER_OVERFLOW:
          // Reset the application buffer size.
          appBBSize = sslEngine.getSession().getApplicationBufferSize();
          break;

        case BUFFER_UNDERFLOW:
          // Resize buffer if needed.
          netBBSize = sslEngine.getSession().getPacketBufferSize();
          if (netBBSize > inNetBB.capacity()) {
            resizeResponseBB();

            break; // break, next read will support larger buffer.
          }
        case OK:
          if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
            doTasks();
          }
          break;

        default:
          throw new IOException("sslEngine error during data read: " + result.getStatus());
      }
    } while ((inNetBB.position() != 0) && result.getStatus() != Status.BUFFER_UNDERFLOW);

    return (requestBB.position() - pos);
  }
Ejemplo n.º 19
0
  public static void main(String[] args) throws Exception {
    outBuf.put("Blah Blah".getBytes());
    outBuf.flip();
    test1();

    // This test has been disabled because there are many circumstances
    // under which no ICMP port unreachable packets are received
    // See http://java.sun.com/j2se/1.4/networking-relnotes.html
    if ((args.length > 0) && (args[0].equals("test2"))) {
      outBuf.rewind();
      test2();
    }
  }
Ejemplo n.º 20
0
 public void run() {
   try {
     // Exclusive lock with no overlap:
     FileLock fl = fc.lock(start, end, false);
     System.out.println("Locked: " + start + " to " + end);
     // Perform modification:
     while (buff.position() < buff.limit() - 1) buff.put((byte) (buff.get() + 1));
     fl.release();
     System.out.println("Released: " + start + " to " + end);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 21
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) {
          if (ProxyConnections != null) {
            EventableChannel target = ProxyConnections.get(b);
            if (target != null) {
              ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit());
              myWriteBuffer.put(myReadBuffer);
              myWriteBuffer.flip();
              target.scheduleOutboundData(myWriteBuffer);
            } else {
              eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
            }
          } else {
            eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
          }
        }
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }
  public static void main(String[] args) throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    DatagramSocket socket = dc.socket();
    socket.bind(new InetSocketAddress(22500));
    ByteBuffer byteBuf = ByteBuffer.allocate(8);
    //        byteBuf.order(ByteOrder.LITTLE_ENDIAN);
    LongBuffer longBuf = byteBuf.asLongBuffer();

    while (true) {
      dc.receive(byteBuf);
      System.out.println(longBuf.get(0));
      byteBuf.clear();
    }
  }
Ejemplo n.º 23
0
 public void write(FileOutputStream fos) throws IOException {
   FileChannel chan = fos.getChannel();
   // Create ByteBuffer for header in case the start of our
   // ByteBuffer isn't actually memory-mapped
   ByteBuffer hdr = ByteBuffer.allocate(Header.writtenSize());
   hdr.order(ByteOrder.LITTLE_ENDIAN);
   header.write(hdr);
   hdr.rewind();
   chan.write(hdr);
   buf.position(Header.writtenSize());
   chan.write(buf);
   chan.force(true);
   chan.close();
 }
Ejemplo n.º 24
0
  public static void main(String[] args) throws IOException {

    FileInputStream fin = new FileInputStream(args[0]);
    GZIPInputStream gzin = new GZIPInputStream(fin);
    ReadableByteChannel in = Channels.newChannel(gzin);

    WritableByteChannel out = Channels.newChannel(System.out);
    ByteBuffer buffer = ByteBuffer.allocate(65536);
    while (in.read(buffer) != -1) {
      buffer.flip();
      out.write(buffer);
      buffer.clear();
    }
  }
  public static void main(String args[]) throws Exception {
    final int ENOUGH_SIZE = 1024;
    final int SMALL_SIZE = 4;

    boolean isBlocked = true;
    int size = ENOUGH_SIZE;

    if (args.length > 0) {
      int opt = Integer.parseInt(args[0]);
      switch (opt) {
        case 1:
          isBlocked = true;
          size = ENOUGH_SIZE;
          break;
        case 2:
          isBlocked = true;
          size = SMALL_SIZE;
          break;
        case 3:
          isBlocked = false;
          size = ENOUGH_SIZE;
          break;
        case 4:
          isBlocked = false;
          size = SMALL_SIZE;
          break;
      }
    }

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(isBlocked);
    ByteBuffer buffer = ByteBuffer.allocate(size);
    DatagramSocket socket = channel.socket();
    SocketAddress localAddr = new InetSocketAddress(8000);
    socket.bind(localAddr);

    while (true) {
      System.out.println("开始接收数据报");
      SocketAddress remoteAddr = channel.receive(buffer);
      if (remoteAddr == null) {
        System.out.println("没有接收到数据报");
      } else {
        buffer.flip();
        System.out.println("接收到的数据报的大小为" + buffer.remaining());
      }
      Thread.sleep(500);
    }
  }
Ejemplo n.º 26
0
  public static void createTestFiles() {
    try {
      System.out.println("Creating test files ... ");
      Random rand = new Random();
      String rootname = "f-";

      long[] sizes = {0, 1, 50000000};

      File testdir = new File(dirname);
      FileUtil.mkdirs(testdir);

      for (int i = 0; i < sizes.length; i++) {
        long size = sizes[i];
        File file = new File(testdir, rootname + String.valueOf(size));
        System.out.println(file.getName() + "...");
        FileChannel fc = new RandomAccessFile(file, "rw").getChannel();

        long position = 0;
        while (position < size) {
          long remaining = size - position;
          if (remaining > 1024000) remaining = 1024000;
          byte[] buffer = new byte[new Long(remaining).intValue()];
          rand.nextBytes(buffer);
          ByteBuffer bb = ByteBuffer.wrap(buffer);
          position += fc.write(bb);
        }

        fc.close();
      }
      System.out.println("DONE\n");
    } catch (Exception e) {
      Debug.printStackTrace(e);
    }
  }
Ejemplo n.º 27
0
 private void readFromBuffer(ByteBuffer buf) throws IOException {
   this.buf = buf;
   buf.order(ByteOrder.LITTLE_ENDIAN);
   header = new Header();
   header.read(buf);
   fixupHeader();
 }
Ejemplo n.º 28
0
  public static void runTests() {
    try {

      // SHA1 sha1Jmule = new SHA1();
      MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1");
      SHA1 sha1Gudy = new SHA1();
      // SHA1Az shaGudyResume = new SHA1Az();

      ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);

      File dir = new File(dirname);
      File[] files = dir.listFiles();

      for (int i = 0; i < files.length; i++) {
        FileChannel fc = new RandomAccessFile(files[i], "r").getChannel();

        System.out.println("Testing " + files[i].getName() + " ...");

        while (fc.position() < fc.size()) {
          fc.read(buffer);
          buffer.flip();

          byte[] raw = new byte[buffer.limit()];
          System.arraycopy(buffer.array(), 0, raw, 0, raw.length);

          sha1Gudy.update(buffer);
          sha1Gudy.saveState();
          ByteBuffer bb = ByteBuffer.wrap(new byte[56081]);
          sha1Gudy.digest(bb);
          sha1Gudy.restoreState();

          sha1Sun.update(raw);

          buffer.clear();
        }

        byte[] sun = sha1Sun.digest();
        sha1Sun.reset();

        byte[] gudy = sha1Gudy.digest();
        sha1Gudy.reset();

        if (Arrays.equals(sun, gudy)) {
          System.out.println("  SHA1-Gudy: OK");
        } else {
          System.out.println("  SHA1-Gudy: FAILED");
        }

        buffer.clear();
        fc.close();
        System.out.println();
      }

    } catch (Throwable e) {
      Debug.printStackTrace(e);
    }
  }
Ejemplo n.º 29
0
 private void recv(SocketChannel sc, ClientInfo ci) throws IOException {
   ci.channel.read(ci.inBuf);
   ByteBuffer tmpBuf = ci.inBuf.duplicate();
   tmpBuf.flip();
   int bytesProcessed = 0;
   boolean doneLoop = false;
   while (!doneLoop) {
     byte b;
     try {
       b = tmpBuf.get();
     } catch (BufferUnderflowException bue) {
       // Processed all data in buffer
       ci.inBuf.clear();
       doneLoop = true;
       break;
     }
     switch (b) {
       case TypeServerConstants.WELCOME:
         bytesProcessed++;
         break;
       case TypeServerConstants.GET_STRING_REQUEST:
         bytesProcessed++;
         if (ci.outputPending) {
           // Client is backed up. We can't append to
           // the byte buffer because it's in the wrong
           // state. We could allocate another buffer
           // here and change our send method to know
           // about multiple buffers, but we'll just
           // assume that the client is dead
           break;
         }
         ci.outBuf.put(TypeServerConstants.GET_STRING_RESPONSE);
         ByteBuffer strBuf = encoder.encode(testString);
         ci.outBuf.putShort((short) strBuf.remaining());
         ci.outBuf.put(strBuf);
         ci.outBuf.flip();
         send(sc, ci);
         break;
       case TypeServerConstants.GET_STRING_RESPONSE:
         int startPos = tmpBuf.position();
         try {
           int nBytes = tmpBuf.getInt();
           byte[] buf = new byte[nBytes];
           tmpBuf.get(buf);
           bytesProcessed += buf.length + 5;
           String s = new String(buf);
           // Send the string to the GUI
           break;
         } catch (BufferUnderflowException bue) {
           // Processed all available data
           ci.inBuf.position(ci.inBuf.position() + bytesProcessed);
           doneLoop = true;
         }
         break;
     }
   }
 }
Ejemplo n.º 30
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }