コード例 #1
0
 @Test
 public void testDecodeWithMessageIdAndAck() throws IOException {
   Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null);
   Assert.assertEquals(PacketType.EVENT, packet.getType());
   Assert.assertEquals(1, (long) packet.getId());
   Assert.assertEquals(Packet.ACK_DATA, packet.getAck());
   Assert.assertEquals("tobi", packet.getName());
 }
コード例 #2
0
  public void notify(Packet packet) {
    Log.trace("Register handling " + packet.toString());

    String type = packet.getType();
    Packet query = packet.getFirstChild("query");

    if (type.equals("get")) {
      required.setSession(packet.getSession());
      required.setID(packet.getID());
      MessageHandler.deliverPacket(required);
      return;

    } else if (type.equals("set")) { // type == set
      String username = query.getChildValue("username");
      User user = userIndex.getUser(username);
      if (user != null) { // user exists
        if (packet.getSession().getStatus() != Session.AUTHENTICATED
            || !username.equals(packet.getSession().getJID().getUser())) {
          Packet iq = new Packet("iq");
          iq.setSession(packet.getSession());
          iq.setID(packet.getID());
          ErrorTool.setError(iq, 401, "User account already exists");
          MessageHandler.deliverPacket(iq);
          return;
        }
      } else {
        user = userIndex.addUser(username);
      }
      user.setPassword(query.getChildValue("password"));
      user.setHash(query.getChildValue("hash"));
      user.setSequence(query.getChildValue("sequence"));
      user.setToken(query.getChildValue("token"));
      if (user.getHash() == null || user.getSequence() == null || user.getToken() == null) {
        if (user.getPassword() != null) {
          user.setToken(Authenticator.randomToken());
          user.setSequence("99");
          user.setHash(
              auth.getZeroKHash(100, user.getToken().getBytes(), user.getPassword().getBytes()));
        }
      } else {
        user.setSequence(Integer.toString(Integer.parseInt(user.getSequence()) - 1));
      }
      Packet iq = new Packet("iq");
      iq.setSession(packet.getSession());
      iq.setID(packet.getID());
      iq.setType("result"); // success
      MessageHandler.deliverPacket(iq);
      Log.trace(
          "Register successfully registered "
              + username
              + " with password "
              + query.getChildValue("password"));
    } else {
      Log.info("Register ignoring " + packet.toString());
    }
  }
コード例 #3
0
 public void handlePacket(byte[] p, String from) {
   Packet s = Packet.createPacket(p);
   s.decreaseHopCount();
   if (s.getHopCount() > 0) {
     Log("SynCore", s.getSource() + " " + s.getDestination());
     if (s.getType() == Packet.DATA_PACKET) {
       handleDataPacket(s);
     } else {
       handleUpdatePacket(s, from);
     }
   }
 }
コード例 #4
0
  @Test
  public void testDecodeWithData() throws IOException {
    JacksonJsonSupport jsonSupport = new JacksonJsonSupport(new Configuration());
    jsonSupport.addEventMapping("edwald", HashMap.class, Integer.class, String.class);
    Decoder decoder = new Decoder(jsonSupport, ackManager);

    Packet packet =
        decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null);
    Assert.assertEquals(PacketType.EVENT, packet.getType());
    Assert.assertEquals("edwald", packet.getName());
    Assert.assertEquals(3, packet.getArgs().size());
    Map obj = (Map) packet.getArgs().get(0);
    Assert.assertEquals("b", obj.get("a"));
    Assert.assertEquals(2, packet.getArgs().get(1));
    Assert.assertEquals("3", packet.getArgs().get(2));
  }
コード例 #5
0
  /**
   * Method description
   *
   * @param ios
   * @param p
   * @return a value of <code>boolean</code>
   */
  public boolean writePacketToSocket(IO ios, Packet p) {
    if (ios != null) {
      if (log.isLoggable(Level.FINER) && !log.isLoggable(Level.FINEST)) {
        log.log(
            Level.FINER,
            "{0}, Processing packet: {1}, type: {2}",
            new Object[] {ios, p.getElemName(), p.getType()});
      }
      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] {ios, p});
      }

      // synchronized (ios) {
      ios.addPacketToSend(p);
      if (ios.writeInProgress.tryLock()) {
        try {
          ios.processWaitingPackets();
          SocketThread.addSocketService(ios);

          return true;
        } catch (Exception e) {
          log.log(Level.WARNING, ios + "Exception during writing packets: ", e);
          try {
            ios.stop();
          } catch (Exception e1) {
            log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1);
          } // end of try-catch
        } finally {
          ios.writeInProgress.unlock();
        }
      }

    } else {
      if (log.isLoggable(Level.FINE)) {
        log.log(
            Level.FINE,
            "Can''t find service for packet: <{0}> {1}, service id: {2}",
            new Object[] {p.getElemName(), p.getTo(), getServiceId(p)});
      }
    } // end of if (ios != null) else

    return false;
  }
コード例 #6
0
  /**
   * Method description
   *
   * @param serv
   * @param packets
   */
  public void writePacketsToSocket(IO serv, Queue<Packet> packets) {
    if (serv != null) {

      // synchronized (serv) {
      if ((packets != null) && (packets.size() > 0)) {
        Packet p = null;

        while ((p = packets.poll()) != null) {
          if (log.isLoggable(Level.FINER) && !log.isLoggable(Level.FINEST)) {
            log.log(
                Level.FINER,
                "{0}, Processing packet: {1}, type: {2}",
                new Object[] {serv, p.getElemName(), p.getType()});
          }
          if (log.isLoggable(Level.FINEST)) {
            log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] {serv, p});
          }
          serv.addPacketToSend(p);
        } // end of for ()
        try {
          serv.processWaitingPackets();
          SocketThread.addSocketService(serv);
        } catch (Exception e) {
          log.log(Level.WARNING, serv + "Exception during writing packets: ", e);
          try {
            serv.stop();
          } catch (Exception e1) {
            log.log(Level.WARNING, serv + "Exception stopping XMPPIOService: ", e1);
          } // end of try-catch
        } // end of try-catch
      }

      // }
    } else {
      if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "Can't find service for packets: [{0}] ", packets);
      }
    } // end of if (ios != null) else
  }
コード例 #7
0
 @Test
 public void testDecode() throws IOException {
   Packet packet = decoder.decodePacket("5:::{\"name\":\"woot\"}", null);
   Assert.assertEquals(PacketType.EVENT, packet.getType());
   Assert.assertEquals("woot", packet.getName());
 }
コード例 #8
0
ファイル: ServerThread.java プロジェクト: qickrooms/varta
  public void run() {
    ObjectInputStream din = null;
    try {
      din = new ObjectInputStream(socket.getInputStream());
      Packet packet = (Packet) din.readObject();
      username = packet.getSender();

      server.usernameSocketMapping.put(username, socket);
      server.isAlive.add(username);
      // Sh: Login validation message
      if (packet.getType() == 0) {
        try {
          String password = packet.getMessage();
          Statement st = Server.conn.createStatement();
          ResultSet rs =
              st.executeQuery(
                  "SELECT * FROM user_info where username='******' and password='******'");
          if (!rs.next()) { // User does not exist
            server.forwardToReceiver(new Packet(0, "Server", username, "Invalid"));
            synchronized (server.usernameSocketMapping) {
              server.usernameSocketMapping.remove(username);
            }
            synchronized (server.isAlive) {
              server.isAlive.remove(username);
            }
            return;
          } else { // Authentic user
            server.forwardToReceiver(new Packet(0, "Server", username, "Authentic"));
          }
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
      // Sh: Signup message
      if (packet.getType() == 2) {
        try {
          String[] message = packet.getMessage().split(":");
          String name = message[0];
          String password = message[1];
          // String sex=message[2];
          String username = message[2];
          Statement st = Server.conn.createStatement();
          ResultSet rs =
              st.executeQuery("SELECT * FROM user_info where username='******'");
          if (rs.next()) { // Username already present
            server.forwardToReceiver(new Packet(2, "Server", username, "Username present"));
            synchronized (server.usernameSocketMapping) {
              server.usernameSocketMapping.remove(username);
            }
            synchronized (server.isAlive) {
              server.isAlive.remove(username);
            }
            return;
          } else { // Register user
            String query =
                "INSERT INTO user_info VALUES('"
                    + name
                    + "','"
                    + password
                    + "',"
                    + "NULL,'"
                    + username
                    + "')";
            System.out.println(query);
            st.executeUpdate(query);
            server.forwardToReceiver(new Packet(2, "Server", username, "User Registererd"));
          }

        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
      System.out.println("State of isAlive map is: " + server.isAlive);

      try {
        Statement st = Server.conn.createStatement();
        ResultSet rs =
            st.executeQuery(
                "SELECT sender,message,status FROM msg_buffer where receiver='"
                    + username
                    + "' order by sender,sno");
        String sendflag = null;
        String sender = null;
        while (rs.next()) {

          sender = rs.getString("sender");
          int status = rs.getInt("status");
          String message = rs.getString("message");
          System.out.println("sender: " + sender);
          System.out.println("receiver: " + username);
          System.out.println("message: " + message);
          server.forwardToReceiver(new Packet(status, sender, username, message));
          System.out.println("Sending " + packet);
          if (!sender.equals(sendflag)) {
            server.forwardToReceiver(new Packet(6, username, sender, "Message Received"));
            sendflag = sender;
          }
        }

        st.executeUpdate("DELETE FROM msg_buffer where receiver='" + username + "'");
      } catch (SQLException e1) {
        e1.printStackTrace();
      }

      while (true) {
        packet = (Packet) din.readObject();

        if (packet.getType() == 3) // is an OK message
        {
          try {
            packet.setSender(username);
            System.out.println("Is OK message");
            Statement st = Server.conn.createStatement();
            ResultSet rs =
                st.executeQuery(
                    "SELECT * FROM user_info where username='******'");
            if (rs.next()) {

              if (server.addFriend(packet.getSender(), packet.getReceiver(), true) == 1) {
                // packet.setMessage("Already in friend list");
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getSender(), "Already in friend list"));
                System.out.println("ALready in list");
              } else {
                System.out.println("Sending " + packet);
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getReceiver(), packet.getMessage()));
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getSender(), packet.getMessage()));
              }
            } else {
              server.forwardToReceiver(
                  new Packet(1, "Server", packet.getSender(), "User does not exist"));
            }
          } catch (SQLException e1) {
            e1.printStackTrace();
          }
        } else if ((packet.getType() == 8)) // is a getFriends message
        {
          packet.setSender(username);
          System.out.println("Type 8");
          /*
           * try { //Thread.sleep(3000); } catch (InterruptedException
           * e) { // TODO Auto-generated catch block
           * e.printStackTrace(); }
           */
          String FriendsMessage = getFriendsMessage(packet);
          server.forwardToReceiver(
              new Packet(8, "Server", packet.getSender(), "Friends|" + FriendsMessage));
        } else if (packet.getType() == 16) // Random conversation.
        {
          packet.setSender(username);
          String receiver = server.getRandomPerson(packet.getSender());
          if (!receiver.equals("No One Online")) {
            server.forwardToReceiver(
                new Packet(1, "Server", packet.getSender(), receiver + "| will talk to you now."));
            server.forwardToReceiver(
                new Packet(1, "Server", receiver, packet.getSender() + "| will talk to you now."));
          } else {
            System.out.println("No one online");
            server.forwardToReceiver(new Packet(16, "Server", packet.getSender(), "No One Online"));
            server.forwardToReceiver(new Packet(1, "Server", packet.getSender(), "No One Online"));
          }
        } else if (packet.getType() == 13) { // Webcam of live is started
          synchronized (server.webcamAliveMapping) {
            server.webcamAliveMapping.put(packet.getSender(), packet.getMessage());
          }
          System.out.println("State of webcamAliveMapping is: " + server.webcamAliveMapping);

        } else if (packet.getType() == 14) { // Webcam of client is
          // closed
          if (server.webcamAliveMapping.containsKey(packet.getSender())) {
            synchronized (server.webcamAliveMapping) {
              server.webcamAliveMapping.remove(packet.getSender());
            }
          }
        } else if (packet.getType() == 15) { // Client requested for
          // another client's webcam
          if (server.webcamAliveMapping.containsKey(
              packet.getReceiver())) { // User Webcam is available
            server.forwardToReceiver(
                new Packet(
                    15,
                    "Server",
                    packet.getSender(),
                    server.webcamAliveMapping.get(packet.getReceiver())));
          } else { // User Webcam not available
            server.forwardToReceiver(
                new Packet(15, "Server", packet.getSender(), "Webcam Not Found"));
            server.forwardToReceiver(
                new Packet(
                    1,
                    "Server",
                    packet.getSender(),
                    "Webcam for " + packet.getReceiver() + " is not available"));
          }
        } else if (packet.getType() == 17) {
          ArrayList<String> friends = new ArrayList<String>();
          friends = server.getfriendlist(packet.getSender());
          if (friends.isEmpty()) {
            server.forwardToReceiver(
                new Packet(1, "Server", packet.getSender(), "Your friendlist is empty."));
          } else {
            for (int i = 0; i < friends.size(); i++) {
              server.forwardToReceiver(
                  new Packet(1, packet.getSender(), friends.get(i), packet.getMessage()));
            }
          }

        } else {
          packet.setSender(username);
          System.out.println("Sending " + packet);
          server.forwardToReceiver(packet);
        }
      }
    } catch (EOFException ie) {
    } catch (IOException ie) {
      ie.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        din.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      synchronized (server.isAlive) {
        server.isAlive.remove(username);
      }
      synchronized (server.usernameSocketMapping) {
        server.usernameSocketMapping.remove(username);
      }
      System.out.println("State of isAlive map is: " + server.isAlive);
      server.removeConnection(socket);
    }
  }
コード例 #9
0
  @Override
  public void encode(IoSession session, Object in, ProtocolEncoderOutput out) throws Exception {
    Packet p = (Packet) in;

    /*
     * Check what type the packet is.
     */
    if (p.isRaw()) {
      /*
       * If the packet is raw, send its payload.
       */
      out.write(p.getPayload());
    } else {
      /*
       * If not, get the out ISAAC cipher.
       */
      // ISAACCipher outCipher = ((Player)
      // session.getAttribute("player")).getOutCipher();

      /*
       * Get the packet attributes.
       */
      int opcode = p.getOpcode();
      Packet.Type type = p.getType();
      int length = p.getLength();

      /*
       * Encrypt the packet opcode.
       */
      // opcode += outCipher.getNextValue();

      /*
       * Compute the required size for the buffer.
       */
      int finalLength = length + 1;
      switch (type) {
        case VARIABLE:
          finalLength += 1;
          break;
        case VARIABLE_SHORT:
          finalLength += 2;
          break;
      }

      /*
       * Create the buffer and write the opcode (and length if the packet
       * is variable-length).
       */
      IoBuffer buffer = IoBuffer.allocate(finalLength);
      buffer.put((byte) opcode);
      switch (type) {
        case VARIABLE:
          buffer.put((byte) length);
          break;
        case VARIABLE_SHORT:
          buffer.putShort((short) length);
          break;
      }

      /*
       * Write the payload itself.
       */
      buffer.put(p.getPayload());

      /*
       * Flip and dispatch the packet.
       */
      out.write(buffer.flip());
    }
  }
コード例 #10
0
  public void encodePacket(
      Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary)
      throws IOException {
    ByteBuf buf = buffer;
    if (!binary) {
      buf = allocateBuffer(allocator);
    }
    byte type = toChar(packet.getType().getValue());
    buf.writeByte(type);

    try {
      switch (packet.getType()) {
        case PONG:
          {
            buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8));
            break;
          }

        case OPEN:
          {
            ByteBufOutputStream out = new ByteBufOutputStream(buf);
            jsonSupport.writeValue(out, packet.getData());
            break;
          }

        case MESSAGE:
          {
            ByteBuf encBuf = null;

            if (packet.getSubType() == PacketType.ERROR) {
              encBuf = allocateBuffer(allocator);

              ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
              jsonSupport.writeValue(out, packet.getData());
            }

            if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK) {

              List<Object> values = new ArrayList<Object>();
              if (packet.getSubType() == PacketType.EVENT) {
                values.add(packet.getName());
              }

              encBuf = allocateBuffer(allocator);

              List<Object> args = packet.getData();
              values.addAll(args);
              ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
              jsonSupport.writeValue(out, values);

              if (!jsonSupport.getArrays().isEmpty()) {
                packet.initAttachments(jsonSupport.getArrays().size());
                for (byte[] array : jsonSupport.getArrays()) {
                  packet.addAttachment(Unpooled.wrappedBuffer(array));
                }
                packet.setSubType(PacketType.BINARY_EVENT);
              }
            }

            byte subType = toChar(packet.getSubType().getValue());
            buf.writeByte(subType);

            if (packet.hasAttachments()) {
              byte[] ackId = toChars(packet.getAttachments().size());
              buf.writeBytes(ackId);
              buf.writeByte('-');
            }

            if (packet.getSubType() == PacketType.CONNECT) {
              if (!packet.getNsp().isEmpty()) {
                buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
              }
            } else {
              if (!packet.getNsp().isEmpty()) {
                buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
                buf.writeByte(',');
              }
            }

            if (packet.getAckId() != null) {
              byte[] ackId = toChars(packet.getAckId());
              buf.writeBytes(ackId);
            }

            if (encBuf != null) {
              buf.writeBytes(encBuf);
              encBuf.release();
            }

            break;
          }
      }
    } finally {
      // we need to write a buffer in any case
      if (!binary) {
        buffer.writeByte(0);
        int length = buf.writerIndex();
        buffer.writeBytes(longToBytes(length));
        buffer.writeByte(0xff);
        buffer.writeBytes(buf);

        buf.release();
      }
    }
  }