コード例 #1
0
  public void handlePacket(Packet p, IoSession session) throws Exception {
    final long uID = ((LSPacket) p).getUID();
    World world = (World) session.getAttachment();
    long user = p.readLong();
    String ip = DataConversions.IPToString(p.readLong());
    byte[] pass = p.readBytes(p.readInt());
    String UID = p.readString();
    byte loginCode = validatePlayer(user, pass, ip, UID);

    builder.setUID(uID);
    if (loginCode == 0 || loginCode == 1 || loginCode == 99) {
      try {
        badClients.add(DataConversions.hashToUsername(user));
        System.out.println("UID: " + UID + " Player: " + DataConversions.hashToUsername(user));
      } catch (Exception e) {
        System.out.println("Exception in UID printer :" + e.getMessage());
      }

      builder.setPlayer(Server.getServer().findSave(user, world), loginCode);
      world.registerPlayer(user, ip, UID);
    } else {
      builder.setPlayer(null, loginCode);
    }

    LSPacket packet = builder.getPacket();
    if (packet != null) {
      session.write(packet);
    }
  }
コード例 #2
0
  /**
   * Called by Status implementations to retrieve the pending notifications and send them to the
   * connected client device
   */
  protected void managePendingNotificationMessage() {
    try {

      String username = (String) session.getAttribute(ATTRIBUTE_USERNAME);
      String deviceId = (String) session.getAttribute(ATTRIBUTE_DEVID);
      if (logger.isTraceEnabled()) {
        logger.trace(
            "Retrieving pending notifications for user '"
                + username
                + "', deviceId: '"
                + deviceId
                + "'");
      }

      com.funambol.framework.notification.Message message =
          pendingNotificationManager.getMessageFromPendingNotifications(username, deviceId);

      if (message == null) {
        if (logger.isTraceEnabled()) {
          logger.trace("No pending notification messages present.");
        }
      } else {
        sendSyncMessage(message.getMessageContent());

        pendingNotificationManager.deletePendingNotifications(
            username, deviceId, message.getSyncSources());
        if (logger.isTraceEnabled()) {
          logger.trace("Pending notifications sent to device " + deviceId);
        }
      }
    } catch (PendingNotificationException ex) {
      logger.error("Error while retrieving pending notification messages", ex);
    }
  }
コード例 #3
0
 /**
  * Invoked when the idle status of a session changes.
  *
  * @param session The session in question
  * @param status The new idle status
  */
 public void sessionIdle(IoSession session, IdleStatus status) {
   Player player = (Player) session.getAttachment();
   if (!player.destroyed()) {
     player.destroy(false);
   }
   session.close();
 }
コード例 #4
0
 public void stop() {
   for (IoSession session : sessions) {
     if (session != null) {
       session.close();
     }
   }
 }
コード例 #5
0
  private void processIncomingPackets() {
    for (RSCPacket p : packetQueue.getPackets()) {
      IoSession session = p.getSession();
      Player player = (Player) session.getAttachment();
      if (player.getUsername() == null && p.getID() != 32 && p.getID() != 77 && p.getID() != 0) {
        final String ip = player.getCurrentIP();
        IPBanManager.throttle(ip);
        continue;
      }
      PacketHandler handler = packetHandlers.get(p.getID());
      player.ping();
      if (handler != null) {
        try {
          handler.handlePacket(p, session);
          try {
            if (p.getID() != 5) {
              // String s = "[PACKET] " +
              // session.getRemoteAddress().toString().replace("/",
              // "") + " : " + p.getID()+
              // " ["+handler.getClass().toString()+"]" + " : "+
              // player.getUsername() + " : ";
              // for(Byte b : p.getData())
              // s += b;
              // Logger.println(s);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }

        } catch (Exception e) {
          String s;
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw, true);
          e.printStackTrace(pw);
          pw.flush();
          sw.flush();
          s = sw.toString();
          Logger.error(
              "Exception with p["
                  + p.getID()
                  + "] from "
                  + player.getUsername()
                  + " ["
                  + player.getCurrentIP()
                  + "]: "
                  + s);
          player.getActionSender().sendLogout();
          player.destroy(false);
        }
      } else {
        Logger.error(
            "Unhandled packet from "
                + player.getCurrentIP()
                + ": "
                + p.getID()
                + "len: "
                + p.getLength());
      }
    }
  }
コード例 #6
0
ファイル: PlayerLogin.java プロジェクト: l3eta/RSCProject
  public void handlePacket(Packet p1, IoSession session) throws Exception {

    Player player = (Player) session.getAttachment();
    final String ip =
        ((InetSocketAddress) session.getRemoteAddress())
            .getAddress()
            .toString()
            .replaceAll("/", "");

    byte loginCode;
    try {

      byte[] data = RSA.decrypt(p1.getData());
      Packet p = new Packet(session, data);

      boolean reconnecting = (p.readByte() == 1);

      int clientVersion = p.readInt();

      if (Config.SERVER_VERSION != clientVersion) {
        Logger.println(
            "ip: " + ip + " | clientversion: " + clientVersion + " : " + Config.SERVER_VERSION);
      }

      int[] sessionKeys = new int[4];
      for (int key = 0; key < sessionKeys.length; key++) {
        sessionKeys[key] = p.readInt();
      }
      String username = "";
      String password = "";

      username = p.readString(20).trim();
      password = p.readString(20).trim();

      if (world.countPlayers() >= Config.MAX_PLAYERS) {
        loginCode = 10;
      } else if (clientVersion < Config.SERVER_VERSION) {
        loginCode = 4;
      } else if (!player.setSessionKeys(sessionKeys)) {
        loginCode = 5;
      } else {
        player.load(username, password, 0, reconnecting);
        if (clientVersion < 39) {
          player.clientWarn(true);
        }
        return;
      }
    } catch (Exception e) {
      System.err.println("Login exception with: " + ip);
      e.printStackTrace();
      loginCode = 4;
    }

    RSCPacketBuilder pb = new RSCPacketBuilder();
    pb.setBare(true);
    pb.addByte((byte) loginCode);
    session.write(pb.toPacket());
    player.destroy(true);
  }
コード例 #7
0
 public Channel getChannel(InetSocketAddress remoteAddress) {
   Set<IoSession> sessions = acceptor.getManagedSessions(getBindAddress());
   for (IoSession session : sessions) {
     if (session.getRemoteAddress().equals(remoteAddress)) {
       return MinaChannel.getOrAddChannel(session, getUrl(), this);
     }
   }
   return null;
 }
コード例 #8
0
  public void sessionCreated(IoSession session) {
    session
        .getFilterChain()
        .addFirst("protocolFilter", new ProtocolCodecFilter(new RSCCodecFactory()));

    Logger.println(
        "Connection from: "
            + ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress());
  }
コード例 #9
0
  private void setLogPrefix(final String userName, final String deviceId, final IoSession session) {

    StringBuilder prefix = new StringBuilder();
    prefix.append("[").append(session.getRemoteAddress()).append("] ");
    prefix.append("[").append(getSessionId()).append("] ");
    prefix.append("[").append(deviceId).append("] ");
    prefix.append("[").append(userName != null ? userName : "").append("] ");
    session.setAttribute(SessionLog.PREFIX, prefix.toString());
    logger.setPrefix(prefix.toString());
  }
コード例 #10
0
 public Collection<Channel> getChannels() {
   Set<IoSession> sessions = acceptor.getManagedSessions(getBindAddress());
   Collection<Channel> channels = new HashSet<Channel>();
   for (IoSession session : sessions) {
     if (session.isConnected()) {
       channels.add(MinaChannel.getOrAddChannel(session, getUrl(), this));
     }
   }
   return channels;
 }
コード例 #11
0
  /**
   * Forward the authentication request to the Authentication Manager
   *
   * @return
   * @throws com.funambol.ctp.server.authentication.AuthenticationException
   */
  protected AuthorizationResponse forwardAuthenticationRequest() throws AuthenticationException {

    String username = (String) session.getAttribute(ATTRIBUTE_USERNAME);
    String deviceId = (String) session.getAttribute(ATTRIBUTE_DEVID);
    String credential = (String) session.getAttribute(ATTRIBUTE_CRED);
    if (logger.isTraceEnabled()) {
      logger.trace("Authenticating user '" + username + "', deviceId: '" + deviceId + "'");
    }
    AuthorizationResponse result =
        authenticationManager.authenticate(username, deviceId, credential);
    return result;
  }
コード例 #12
0
  public void messageReceived(IoSession session, Object message) {
    Player player = (Player) session.getAttachment();
    if (session.isClosing() || player.destroyed()) {
      return;
    }
    RSCPacket p = (RSCPacket) message;

    if (p.getID() == 55) player.addInterval();

    Instance.loggingService().tell(p, ActorRef.noSender());

    packets.add(p);
  }
コード例 #13
0
ファイル: ListPlayers.java プロジェクト: l3eta/RSCProject
  public void handlePacket(Packet p, final IoSession session) throws Exception {
    String[] params = ((FPacket) p).getParameters();
    try {
      final int worldID = Integer.parseInt(params[0]);
      System.out.println("Frontend requested player list for world " + worldID);
      World world = Server.getServer().getWorld(worldID);
      if (world == null) {
        throw new Exception("Unknown world");
      }
      world
          .getActionSender()
          .playerListRequest(
              new PacketHandler() {
                public void handlePacket(Packet p, IoSession s) throws Exception {
                  builder.setID(1);

                  ArrayList<String> params = new ArrayList<String>();
                  int count = p.readInt();
                  for (int c = 0; c < count; c++) {
                    params.add(
                        p.readLong() + "," + p.readShort() + "," + p.readShort() + "," + worldID);
                  }
                  builder.setParameters(params.toArray(new String[params.size()]));

                  session.write(builder.toPacket());
                }
              });
    } catch (Exception e) {
      builder.setID(0);
      session.write(builder.toPacket());
    }
  }
コード例 #14
0
 /**
  * Invoked whenever a packet is ready to be added to the queue.
  *
  * @param session The IO session on which the packet was received
  * @param message The packet
  */
 public void messageReceived(IoSession session, Object message) {
   if (session.isClosing()) {
     return;
   }
   LSPacket p = (LSPacket) message;
   connector.getPacketQueue().add(p);
 }
コード例 #15
0
ファイル: MllpEndpoint.java プロジェクト: turp1twin/ipf
 @Override
 public void run(IoSession session) {
   if (isAudit()) {
     String hostAddress = session.getRemoteAddress().toString();
     getServerAuditStrategy().auditAuthenticationNodeFailure(hostAddress);
   }
 }
コード例 #16
0
 @Override
 public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
   if (!isConnectionOk(session)) {
     session.close();
     return;
   }
   nextFilter.sessionCreated(session);
 }
コード例 #17
0
  /**
   * Creates a new instance of <CODE>SessionManager</CODE>
   *
   * <p>The authentication manager is retrieved from the CTPServerConfiguration using parameter
   * specifide in file config/com/funambol/ctp/server/authentication/AuthenticationManager.xml
   *
   * @param session The related IoSession
   * @param dispatcher The NotificationProvider where to subscribe for notification messages.
   */
  public SessionManager(IoSession session, NotificationProvider dispatcher) {
    this.session = session;
    this.dispatcher = dispatcher;
    this.sessionState = new StateConnected();
    this.sessionId = createSessionId();
    lastClientEventTime = System.currentTimeMillis();

    this.authenticationManager =
        CTPServerConfiguration.getCTPServerConfiguration().getAuthenticationManager();

    this.pendingNotificationManager =
        CTPServerConfiguration.getCTPServerConfiguration().getPendingNotificationManager();

    session.setAttribute(SessionLog.LOGGER, logger);

    String prefix = "[" + session.getRemoteAddress() + "] ";
    session.setAttribute(SessionLog.PREFIX, prefix);
    logger.setPrefix(prefix);
  }
コード例 #18
0
ファイル: LoginConnector.java プロジェクト: l3eta/RSCProject
 public synchronized void sendQueuedPackets() {
   try {
     List<LSPacket> packets = actionSender.getPackets();
     for (LSPacket packet : packets) {
       session.write(packet);
     }
     actionSender.clearPackets();
   } catch (Exception e) {
     Logger.println("Stack processInc: ");
     e.printStackTrace();
   }
 }
コード例 #19
0
ファイル: Ping.java プロジェクト: Marwolf/Wolf-Kingdom
 public void handlePacket(Packet p, IoSession session) throws Exception {
   Player player = (Player) session.getAttachment();
   if (p.getLength() > 0) {
     byte b = p.readByte();
     if (b == 1) { // 1 is for SCAR.
       if (player.sessionFlags < 1) {
         Logger.println(player.getUsername() + " is using SCAR!");
         player.sessionFlags++;
       }
     }
   }
 }
コード例 #20
0
  protected void forwardSubscription() {
    String deviceId = (String) session.getAttribute(ATTRIBUTE_DEVID);
    if (deviceId == null || "".equals(deviceId)) {
      logger.error("Unable to retrieve device id from session attributes");
      closeSession();
      return;
    }

    dispatcher.subscribe(deviceId, this);
    if (logger.isTraceEnabled()) {
      logger.trace("Subscribed notification for device " + deviceId);
    }
  }
コード例 #21
0
ファイル: MinaHelper.java プロジェクト: nilsotto/camel
 /**
  * Writes the given body to MINA session. Will wait until the body has been written.
  *
  * @param session the MINA session
  * @param body the body to write (send)
  * @param exchange the exchange
  * @throws CamelExchangeException is thrown if the body could not be written for some reasons (eg
  *     remote connection is closed etc.)
  */
 public static void writeBody(IoSession session, Object body, Exchange exchange)
     throws CamelExchangeException {
   // the write operation is asynchronous. Use WriteFuture to wait until the session has been
   // written
   WriteFuture future = session.write(body);
   // must use a timeout (we use 10s) as in some very high performance scenarios a write can cause
   // thread hanging forever
   LOG.trace("Waiting for write to complete");
   future.join(10 * 1000L);
   if (!future.isWritten()) {
     LOG.warn("Cannot write body: " + body + " using session: " + session);
     throw new CamelExchangeException("Cannot write body", exchange);
   }
 }
コード例 #22
0
  public synchronized void onAuthenticationReq(Auth auth) {

    setLastClientEventTime(System.currentTimeMillis());

    String deviceId = auth.getDevid();
    if (deviceId == null || "".equals(deviceId)) {
      sendErrorMessage(
          Auth.PARAM_DEVID + " parameter is mandatory for " + auth.getName() + " messages");
      setSessionState(new StateLeaving());
      return;
    }

    String username = auth.getUsername();
    if (username == null || "".equals(username)) {
      sendErrorMessage(
          Auth.PARAM_USERNAME + " parameter is mandatory for " + auth.getName() + " messages");
      setSessionState(new StateLeaving());
      return;
    }

    String credential = auth.getCred();
    if (credential == null || "".equals(credential)) {
      sendErrorMessage(
          Auth.PARAM_CRED + " parameter is mandatory for " + auth.getName() + " messages");
      setSessionState(new StateLeaving());
      return;
    }

    setLogPrefix(username, deviceId, session);

    session.setAttribute(ATTRIBUTE_DEVID, deviceId);
    session.setAttribute(ATTRIBUTE_USERNAME, username);
    session.setAttribute(ATTRIBUTE_CRED, credential);

    State nextState = sessionState.onAuthenticationReq(this, auth);
    setSessionState(nextState);
  }
コード例 #23
0
 public void handlePacket(Packet p, IoSession session) throws Exception {
   Player player = (Player) session.getAttachment();
   Player affectedPlayer = world.getPlayer(p.readShort());
   if (affectedPlayer == null) {
     player.setSuspiciousPlayer(true);
     return;
   }
   if (player.isBusy()) {
     player.resetPath();
     return;
   }
   player.resetAll();
   player.setFollowing(affectedPlayer, 1);
   player.getActionSender().sendMessage("Now following " + affectedPlayer.getUsername());
 }
コード例 #24
0
  public void sendRequest(String request) {
    if (session == null) {
      engine.error("not connected");
    } else {
      session.write(request);

      synchronized (engine) {
        try {
          engine.wait(30000);
        } catch (InterruptedException e) {
          // ignore
        }
      }
    }
  }
コード例 #25
0
  @Override
  protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
      throws Exception {
    // Get the XML light parser from the IoSession
    XMLLightweightParser parser =
        (XMLLightweightParser) session.getAttribute(ConnectionHandler.XML_PARSER);
    // Parse as many stanzas as possible from the received data
    parser.read(in);

    if (parser.areThereMsgs()) {
      for (String stanza : parser.getMsgs()) {
        out.write(stanza);
      }
    }
    return !in.hasRemaining();
  }
コード例 #26
0
ファイル: MinaLoggingFilter.java プロジェクト: koem/Zimbra
 @Override
 public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) {
   ZimbraLog.addIpToContext(session.getRemoteAddress().toString());
   String msg = "Exception caught: " + cause;
   if (isSocketError(cause)) {
     // If connection error, then only log full stack trace if debug enabled
     if (log.isDebugEnabled()) {
       log.info(msg, cause);
     } else {
       log.info(msg);
     }
   } else {
     log.error(msg, cause);
   }
   nextFilter.exceptionCaught(session, cause);
 }
  /*
   * (non-Javadoc)
   *
   * @see org.apache.mina.common.IoFilterAdapter#messageReceived(org.apache.mina.common.IoFilter.NextFilter,
   *      org.apache.mina.common.IoSession, java.lang.Object)
   */
  @Override
  public void messageReceived(NextFilter nextFilter, IoSession session, Object message)
      throws Exception {
    if (message instanceof RtspRequest) {
      RtspRequest req = (RtspRequest) message;

      logger.debug("having RTSP request message, message=" + req);
      if (req.getVerb() == RtspRequest.Verb.SETUP) {
        logger.debug("having SETUP request");

        if (req.getUrl() != null) {
          URL url = req.getUrl();

          logger.debug("requesting setup for " + url);
          session.setAttribute(SessionAttribute, url);
        }
      }
    }

    nextFilter.messageReceived(session, message);
  }
コード例 #28
0
 private InetAddress getAddress(IoSession io) {
   return ((InetSocketAddress) io.getRemoteAddress()).getAddress();
 }
コード例 #29
0
 protected void closeSession() {
   logger.warn("Closing session");
   session.close();
 }
コード例 #30
0
 private void write(Message message) {
   session.write(message);
 }