Esempio n. 1
0
  /**
   * there is a socket listening on the port for this packet. process if it is a new connection rdp
   * packet
   */
  public void processNewConnection(RDPServerSocket serverSocket, RDPPacket packet) {
    if (Log.loggingNet)
      Log.net(
          "processNewConnection: RDPPACKET (localport=" + serverSocket.getPort() + "): " + packet);

    //        int localPort = serverSocket.getPort();
    InetAddress remoteAddr = packet.getInetAddress();
    int remotePort = packet.getPort();
    if (!packet.isSyn()) {
      // the client is not attemping to start a new connection
      // send a reset and forget about it
      Log.debug("socket got non-syn packet, replying with reset: packet=" + packet);
      RDPPacket rstPacket = RDPPacket.makeRstPacket();
      rstPacket.setPort(remotePort);
      rstPacket.setInetAddress(remoteAddr);
      RDPServer.sendPacket(serverSocket.getDatagramChannel(), rstPacket);
      return;
    }

    // it is a syn packet, lets make a new connection for it
    RDPConnection con = new RDPConnection();
    DatagramChannel dc = serverSocket.getDatagramChannel();
    con.initConnection(dc, packet);

    // add new connection to allConnectionMap
    registerConnection(con, dc);

    // ack it with a syn
    RDPPacket synPacket = RDPPacket.makeSynPacket(con);
    con.sendPacketImmediate(synPacket, false);
  }
Esempio n. 2
0
 public void run() {
   while (true) {
     LinkedList<PacketCallbackStruct> list = null;
     try {
       queuedPacketCallbacksLock.lock();
       try {
         queuedPacketCallbacksNotEmpty.await();
       } catch (Exception e) {
         Log.error(
             "RDPServer.PacketCallbackThread: queuedPacketCallbacksNotEmpty.await() caught exception "
                 + e.getMessage());
       }
       list = queuedPacketCallbacks;
       queuedPacketCallbacks = new LinkedList<PacketCallbackStruct>();
     } finally {
       queuedPacketCallbacksLock.unlock();
     }
     if (Log.loggingNet)
       Log.net("RDPServer.PacketCallbackThread: Got " + list.size() + " queued packets");
     for (PacketCallbackStruct pcs : list) {
       try {
         callbackProcessPacket(pcs.cb, pcs.con, pcs.packet);
       } catch (Exception e) {
         Log.exception("RDPServer.PacketCallbackThread: ", e);
       }
     }
   }
 }
Esempio n. 3
0
    public int compareTo(Object arg0) {
      RDPConnectionData other = (RDPConnectionData) arg0;

      if (this.readyTime < other.readyTime) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: readyTime compare -1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con
                  + ", thisready="
                  + this.readyTime
                  + ", otherReady="
                  + other.readyTime);
        return -1;
      } else if (this.readyTime > other.readyTime) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: readyTime compare 1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con
                  + ", thisready="
                  + this.readyTime
                  + ", otherReady="
                  + other.readyTime);
        return 1;
      }

      if (this.con == other.con) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: conRef compare 0: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return 0;
      } else if (this.con.hashCode() < other.con.hashCode()) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: hashCode compare -1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return -1;
      } else if (this.con.hashCode() > other.con.hashCode()) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: hashCode compare 1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return 1;
      } else {
        throw new RuntimeException("error");
      }
    }
Esempio n. 4
0
 /**
  * a DatagramChannel has data ready - process all the pending packets, whether its for a
  * rdpserversocket or rdpconnection.
  */
 void processActiveChannel(DatagramChannel dc) throws ClosedChannelException {
   RDPPacket packet;
   int count = 0;
   // read in the packet
   try {
     Set<RDPConnection> needsAckConnections = new HashSet<RDPConnection>();
     while ((packet = RDPServer.receivePacket(dc)) != null) {
       if (Log.loggingNet)
         Log.net(
             "RDPServer.processActiveChannel: Starting iteration with count of "
                 + count
                 + " packets");
       // see if there is a connection already for this packet
       InetAddress remoteAddr = packet.getInetAddress();
       int remotePort = packet.getPort();
       int localPort = dc.socket().getLocalPort();
       ConnectionInfo conInfo = new ConnectionInfo(remoteAddr, remotePort, localPort);
       RDPConnection con = RDPServer.getConnection(dc, conInfo);
       if (con != null) {
         if (Log.loggingNet)
           Log.net("RDPServer.processActiveChannel: found an existing connection: " + con);
         count++;
         if (processExistingConnection(con, packet)) needsAckConnections.add(con);
         // Prevent this from blocking getActiveChannels by
         // putting an upper bound on the number of packets
         // processed
         if (count >= 20) break;
         continue;
       } else {
         Log.net("RDPServer.processActiveChannel: did not find an existing connection");
       }
       // there is no connection,
       // see if there is a socket listening for new connection
       RDPServerSocket rdpSocket = RDPServer.getRDPSocket(dc);
       if (rdpSocket != null) {
         count++;
         processNewConnection(rdpSocket, packet);
         return;
       }
       return;
     }
     // Finally, send out the acks
     for (RDPConnection con : needsAckConnections) {
       RDPPacket replyPacket = new RDPPacket(con);
       con.sendPacketImmediate(replyPacket, false);
     }
   } catch (ClosedChannelException ex) {
     Log.error("RDPServer.processActiveChannel: ClosedChannel " + dc.socket());
     throw ex;
   } finally {
     if (Log.loggingNet)
       Log.net("RDPServer.processActiveChannel: Returning after processing " + count + " packets");
   }
 }
Esempio n. 5
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache
   * .mina.core.session.IoSession)
   */
  public void sessionCreated(IoSession session) throws Exception {
    String remote = session.getRemoteAddress().toString();
    log.info("stub created:" + remote);

    /** check the allow ip */
    if (TConn.ALLOW_IP == null || "*".equals(TConn.ALLOW_IP) || remote.matches(TConn.ALLOW_IP)) {
      TConn d = new TConn(session);
      session.setAttribute("conn", d);
    } else {
      log.warn("deny the connection:" + remote + ", allow ip:" + TConn.ALLOW_IP);
      session.close(true);
    }
  }
Esempio n. 6
0
  /**
   * Connect by tcp.
   *
   * @param host the host
   * @param port the port
   * @return the t conn
   */
  public static synchronized TConn connectByTcp(String host, int port, long timeout) {

    TimeStamp t = TimeStamp.create();

    try {
      if (tcpconnector == null) {
        tcpconnector = new TDCConnector();
      }

      tcpconnector.connector.setConnectTimeoutMillis(timeout);

      ConnectFuture connFuture = tcpconnector.connector.connect(new InetSocketAddress(host, port));

      connFuture.awaitUninterruptibly(timeout);
      IoSession session = connFuture.getSession();

      TConn c = new TConn(session);

      session.setAttribute("conn", c);
      return c;
    } catch (Exception e) {
      log.error(
          "error, [" + host + ":" + port + "], cost: " + t.past() + "ms, timeout=" + timeout, e);
    }

    return null;
  }
Esempio n. 7
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#sessionClosed(org.apache
  * .mina.core.session.IoSession)
  */
 public void sessionClosed(IoSession session) throws Exception {
   log.debug("closed stub: " + session.getRemoteAddress());
   TConn d = (TConn) session.getAttribute("conn");
   if (d != null) {
     d.close();
   }
 }
Esempio n. 8
0
  /** make sure the packet as the remote address and remote port set */
  static void sendPacket(DatagramChannel dc, RDPPacket packet) {

    sendMeter.add();

    // allocate a buffer
    int bufSize = 100 + (packet.numEacks() * 4);
    if (packet.getData() != null) {
      bufSize += packet.getData().length;
      sendDataMeter.add();
    }
    MVByteBuffer buf = new MVByteBuffer(bufSize);
    packet.toByteBuffer(buf); // function flips the buffer

    int remotePort = packet.getPort();
    InetAddress remoteAddr = packet.getInetAddress();

    if ((remotePort < 0) || (remoteAddr == null)) {
      throw new MVRuntimeException("RDPServer.sendPacket: remotePort or addr is null");
    }

    try {
      int bytes = dc.send(buf.getNioBuf(), new InetSocketAddress(remoteAddr, remotePort));
      if (bytes == 0) {
        Log.error("RDPServer.sendPacket: could not send packet, size=" + bufSize);
      }

      if (Log.loggingNet)
        Log.net(
            "RDPServer.sendPacket: remoteAddr="
                + remoteAddr
                + ", remotePort="
                + remotePort
                + ", numbytes sent="
                + bytes);
    } catch (java.io.IOException e) {
      Log.exception(
          "RDPServer.sendPacket: remoteAddr="
              + remoteAddr
              + ", remotePort="
              + remotePort
              + ", got exception",
          e);
      throw new MVRuntimeException("RDPServer.sendPacket", e);
    }
  }
Esempio n. 9
0
  /**
   * Instantiates a new MDC server.
   *
   * @param host the host
   * @param port the port
   */
  protected MDCServer(String host, int port) {
    _conf = Config.getConfig();

    address = (host == null) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);

    /** initialize app command */
    Command.init();

    /** initialize the connection center */
    TConnCenter.init(_conf, port);

    synchronized (_conf) {
      /** load public key from database */
      TConn.pub_key = SystemConfig.s("pub_key", null);
      TConn.pri_key = SystemConfig.s("pri_key", null);

      /** initialize the RSA key, hardcode 2048 bits */
      if (TConn.pub_key == null
          || TConn.pri_key == null
          || "".equals(TConn.pub_key)
          || "".equals(TConn.pri_key)) {
        /** print out the old state */
        log.warn(
            "the pub_key or pri_key missed, the old state are pub_key:["
                + TConn.pub_key
                + "], pri_key:["
                + TConn.pri_key
                + "]");

        Key k = RSA.generate(2048);
        TConn.pri_key = k.pri_key;
        TConn.pub_key = k.pub_key;

        /** print out the new public key */
        log.warn("create new RSA key pair, pub_key:[" + TConn.pub_key + ']');

        /** set back in database */
        SystemConfig.setConfig("pri_key", TConn.pri_key);
        SystemConfig.setConfig("pub_key", TConn.pub_key);
      }

      MAX_SIZE = SystemConfig.i("mdc.max_size", MAX_SIZE);
    }
  }
Esempio n. 10
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache
   * .mina.core.session.IoSession)
   */
  public void sessionCreated(IoSession session) throws Exception {
    log.info("stub created:" + session.getRemoteAddress());

    Counter.add("mdc", "connection", 1);

    TConn d = new TConn(session);
    d.set("x-forwarded-for", session.getRemoteAddress().toString());

    session.setAttribute("conn", d);
  }
Esempio n. 11
0
 public boolean equals(Object obj) {
   int rv = this.compareTo(obj);
   if (Log.loggingNet)
     Log.net(
         "RDPServer.RDPConnectionData.equals: thisObj="
             + this.toString()
             + ", other="
             + obj.toString()
             + ", result="
             + rv);
   return (rv == 0);
 }
Esempio n. 12
0
 public static void startRDPServer() {
   if (rdpServerStarted) return;
   rdpServerStarted = true;
   rdpServerThread = new Thread(rdpServer, "RDPServer");
   retryThread = new Thread(new RetryThread(), "RDPRetry");
   packetCallbackThread = new Thread(new PacketCallbackThread(), "RDPCallback");
   if (Log.loggingNet) Log.net("static - starting rdpserver thread");
   try {
     selector = Selector.open();
   } catch (Exception e) {
     Log.exception("RDPServer caught exception opening selector", e);
     System.exit(1);
   }
   rdpServerThread.setPriority(rdpServerThread.getPriority() + 2);
   if (Log.loggingDebug)
     Log.debug(
         "RDPServer: starting rdpServerThread with priority " + rdpServerThread.getPriority());
   rdpServerThread.start();
   retryThread.start();
   packetCallbackThread.start();
 }
Esempio n. 13
0
  /** Close. */
  public void close() {
    if (selector != null) {
      selector.wakeup();
      try {
        selector.close();
      } catch (IOException e1) {
        log.warn("close selector fails", e1);
      } finally {
        selector = null;
      }
    }

    if (server != null) {
      try {
        server.socket().close();
        server.close();
      } catch (IOException e) {
        log.warn("close socket server fails", e);
      } finally {
        server = null;
      }
    }
  }
Esempio n. 14
0
 static void callbackProcessPacket(
     ClientConnection.MessageCallback pcb, ClientConnection clientCon, RDPPacket packet) {
   if (packet.isNul()) {
     return;
   }
   byte[] data = packet.getData();
   MVByteBuffer buf = new MVByteBuffer(data);
   RDPConnection con = (RDPConnection) clientCon;
   // If this is a multiple-message message . . .
   if (buf.getLong() == -1 && buf.getInt() == RDPConnection.aggregatedMsgId) {
     con.aggregatedReceives++;
     PacketAggregator.allAggregatedReceives++;
     // Get the count of sub buffers
     int size = buf.getInt();
     con.receivedMessagesAggregated += size;
     PacketAggregator.allReceivedMessagesAggregated += size;
     if (Log.loggingNet)
       Log.net(
           "RDPServer.callbackProcessPacket: processing aggregated message with "
               + size
               + " submessages");
     MVByteBuffer subBuf = null;
     for (int i = 0; i < size; i++) {
       try {
         subBuf = buf.getByteBuffer();
       } catch (Exception e) {
         Log.error("In CallbackThread, error getting aggregated subbuffer: " + e.getMessage());
       }
       if (subBuf != null) pcb.processPacket(con, subBuf);
     }
   } else {
     con.unaggregatedReceives++;
     PacketAggregator.allUnaggregatedReceives++;
     buf.rewind();
     pcb.processPacket(con, buf);
   }
 }
Esempio n. 15
0
 /** starts the server listens to incoming packets */
 public void run() {
   try {
     while (true) {
       if (Log.loggingNet) Log.net("In RDPServer.run: starting new iteration");
       try {
         Set<DatagramChannel> activeChannels = getActiveChannels();
         activeChannelCalls++;
         Iterator<DatagramChannel> iter = activeChannels.iterator();
         while (iter.hasNext()) {
           DatagramChannel dc = iter.next();
           if (Log.loggingNet) Log.net("In RDPServer.run: about to call processActiveChannel");
           processActiveChannel(dc);
           if (Log.loggingNet) Log.net("In RDPServer.run: returned from processActiveChannel");
         }
       } catch (ClosedChannelException ex) {
         // ignore
       } catch (Exception e) {
         Log.exception("RDPServer.run caught exception", e);
       }
     }
   } finally {
     Log.warn("RDPServer.run: thread exiting");
   }
 }
Esempio n. 16
0
  /**
   * returns the RDPConnection that is registered for the given datagram channel and is connected to
   * the host/port in ConnectionInfo returns null if there is no matching registered rdpconnection
   */
  static RDPConnection getConnection(DatagramChannel dc, ConnectionInfo conInfo) {
    lock.lock();
    try {
      Map<ConnectionInfo, RDPConnection> dcConMap = allConMap.get(dc);

      if (dcConMap == null) {
        // there isnt even a datagram associated
        if (Log.loggingNet) Log.net("RDPServer.getConnection: could not find datagram");
        return null;
      }
      return dcConMap.get(conInfo);
    } finally {
      lock.unlock();
    }
  }
Esempio n. 17
0
  /** rdpserversocket wants to bind on a local port */
  static DatagramChannel bind(Integer port, int receiveBufferSize)
      throws java.net.BindException, java.io.IOException, java.net.SocketException {
    lock.lock();
    try {
      // see if there is an existing datagramchannel bound to this port
      DatagramChannel dc = channelMap.get(port);
      if (dc != null) {
        throw new java.net.BindException("RDPServer.bind: port is already used");
      }

      // make a new datagram channel
      dc = DatagramChannel.open();
      dc.configureBlocking(false);
      dc.socket().setReceiveBufferSize(receiveBufferSize);
      if (port == null) {
        if (Log.loggingNet) Log.net("RDPServer.bind: binding to a random system port");
        dc.socket().bind(null);
      } else {
        if (Log.loggingNet) Log.net("RDPServer.bind: binding to port " + port);
        dc.socket().bind(new InetSocketAddress(port));
      }
      int resultingPort = dc.socket().getLocalPort();
      if (Log.loggingNet) Log.net("RDPServer.bind: resulting port=" + resultingPort);

      // add the channel to the channel map
      channelMap.put(resultingPort, dc);
      if (Log.loggingNet) Log.net("RDPServer.bind: added dc to channel map");

      // add the channel to the newChannelsSet
      // we want to register this channel with the selector
      // but the selector thread needs to do that,
      // so place it in this set, and wake up the selector
      newChannelSet.add(dc);
      if (Log.loggingNet) Log.net("RDPServer.bind: added dc to newChannelSet");

      // in case the rdpserver was waiting while it had no sockets,
      // signal it
      channelMapNotEmpty.signal();
      Log.net("RDPServer.bind: signalled channel map not empty condition");

      // wakeup the selector -
      // it needs to register the new channel with itself
      selector.wakeup();

      if (Log.loggingNet) Log.net("RDPServer.bind: woke up selector");
      return dc;
    } finally {
      lock.unlock();
    }
  }
Esempio n. 18
0
  /** Close. */
  public void close() {
    if (selector != null) {
      selector.wakeup();
      try {
        selector.close();
      } catch (IOException e1) {
        log.warn("close selector fails", e1);
      } finally {
        selector = null;
      }
    }

    if (connector != null) {
      connector.dispose();
      connector = null;
    }
  }
Esempio n. 19
0
  /**
   * Connect by udp.
   *
   * @param host the host
   * @param port the port
   * @return the t conn
   */
  public static synchronized TConn connectByUdp(String host, int port) {
    try {
      if (udpconnector == null) {
        udpconnector = new UDCConnector();
      }

      ConnectFuture connFuture = udpconnector.connector.connect(new InetSocketAddress(host, port));
      connFuture.awaitUninterruptibly();
      IoSession session = connFuture.getSession();

      TConn c = new TConn(session);

      session.setAttribute("conn", c);
      return c;
    } catch (Exception e) {
      log.error("[" + host + ":" + port + "]", e);
    }
    return null;
  }
Esempio n. 20
0
  /** the conn data should already be set (remote addr, etc) */
  static void registerConnection(RDPConnection con, DatagramChannel dc) {
    lock.lock();
    try {
      if (Log.loggingNet) Log.net("RDPServer.registerConnection: registering con " + con);

      // first we get the set of connections attached to the given dc
      Map<ConnectionInfo, RDPConnection> dcConMap = allConMap.get(dc);
      if (dcConMap == null) {
        dcConMap = new HashMap<ConnectionInfo, RDPConnection>();
      }

      // add this connection to the map
      int localPort = con.getLocalPort();
      int remotePort = con.getRemotePort();
      InetAddress remoteAddr = con.getRemoteAddr();
      ConnectionInfo conInfo = new ConnectionInfo(remoteAddr, remotePort, localPort);
      dcConMap.put(conInfo, con);
      allConMap.put(dc, dcConMap);
    } finally {
      lock.unlock();
    }
  }
Esempio n. 21
0
  /**
   * removes this connection from the connections map the datagram channel still sticks around in
   * case it needs to be reused
   */
  static void removeConnection(RDPConnection con) {
    lock.lock();
    try {
      if (Log.loggingNet) Log.net("RDPServer.removeConnection: removing con " + con);
      con.setState(RDPConnection.CLOSED);

      DatagramChannel dc = con.getDatagramChannel();

      // first we get the set of connections attached to the given dc
      Map<ConnectionInfo, RDPConnection> dcConMap = allConMap.get(dc);
      if (dcConMap == null) {
        throw new MVRuntimeException("RDPServer.removeConnection: cannot find dc");
      }

      int localPort = con.getLocalPort();
      int remotePort = con.getRemotePort();
      InetAddress remoteAddr = con.getRemoteAddr();
      ConnectionInfo conInfo = new ConnectionInfo(remoteAddr, remotePort, localPort);
      Object rv = dcConMap.remove(conInfo);
      if (rv == null) {
        throw new MVRuntimeException("RDPServer.removeConnection: could not find the connection");
      }

      // close the datagramchannel if needed
      // conditions: no other connections on this datagramchannel
      // no socket listening on this datagramchannel
      if (dcConMap.isEmpty()) {
        Log.net("RDPServer.removeConnection: no other connections for this datagramchannel (port)");
        // there are no more connections on this datagram channel
        // check if there is a serversocket listening
        if (getRDPSocket(dc) == null) {
          Log.net("RDPServer.removeConnection: no socket listening on this port - closing");
          // no socket either, close the datagramchannel
          dc.socket().close();
          channelMap.remove(localPort);
          Log.net("RDPServer.removeConnection: closed and removed datagramchannel/socket");
        } else {
          Log.net("RDPServer.removeConnection: there is a socket listening on this port");
        }
      } else {
        Log.net("RDPServer.removeConnection: there are other connections on this port");
      }
    } finally {
      lock.unlock();
    }
  }
Esempio n. 22
0
    public void run() {
      // every second, go through all the packets that havent been
      // ack'd
      List<RDPConnection> conList = new LinkedList<RDPConnection>();
      long lastCounterTime = System.currentTimeMillis();
      while (true) {
        try {
          long startTime = System.currentTimeMillis();
          long interval = startTime - lastCounterTime;
          if (interval > 1000) {

            if (Log.loggingNet) {
              Log.net(
                  "RDPServer counters: activeChannelCalls "
                      + activeChannelCalls
                      + ", selectCalls "
                      + selectCalls
                      + ", transmits "
                      + transmits
                      + ", retransmits "
                      + retransmits
                      + " in "
                      + interval
                      + "ms");
            }
            activeChannelCalls = 0;
            selectCalls = 0;
            transmits = 0;
            retransmits = 0;
            lastCounterTime = startTime;
          }
          if (Log.loggingNet) Log.net("RDPServer.RETRY: startTime=" + startTime);

          // go through all the rdpconnections and re-send any
          // unacked packets
          conList.clear();

          lock.lock();
          try {
            // make a copy since the values() collection is
            // backed by the map
            Set<RDPConnection> conCol = RDPServer.getAllConnections();
            if (conCol == null) {
              throw new MVRuntimeException("values() returned null");
            }
            conList.addAll(conCol); // make non map backed copy
          } finally {
            lock.unlock();
          }

          Iterator<RDPConnection> iter = conList.iterator();
          while (iter.hasNext()) {
            RDPConnection con = iter.next();
            long currentTime = System.currentTimeMillis();

            // is the connection in CLOSE_WAIT
            if (con.getState() == RDPConnection.CLOSE_WAIT) {
              long closeTime = con.getCloseWaitTimer();
              long elapsedTime = currentTime - closeTime;
              Log.net(
                  "RDPRetryThread: con is in CLOSE_WAIT: elapsed close timer(ms)="
                      + elapsedTime
                      + ", waiting for 30seconds to elapse. con="
                      + con);
              if (elapsedTime > 30000) {
                // close the connection
                Log.net("RDPRetryThread: removing CLOSE_WAIT connection. con=" + con);
                removeConnection(con);
              } else {
                Log.net(
                    "RDPRetryThread: time left on CLOSE_WAIT timer: "
                        + (30000 - (currentTime - closeTime)));
              }
              // con.close();
              continue;
            }
            if (Log.loggingNet)
              Log.net(
                  "RDPServer.RETRY: resending expired packets "
                      + con
                      + " - current list size = "
                      + con.unackListSize());

            // see if we should send a null packet, but only if con is already open
            if ((con.getState() == RDPConnection.OPEN)
                && ((currentTime - con.getLastNullPacketTime()) > 30000)) {
              con.getLock().lock();
              try {
                RDPPacket nulPacket = RDPPacket.makeNulPacket();
                con.sendPacketImmediate(nulPacket, false);
                con.setLastNullPacketTime();
                if (Log.loggingNet) Log.net("RDPServer.retry: sent nul packet: " + nulPacket);
              } finally {
                con.getLock().unlock();
              }
            } else {
              if (Log.loggingNet)
                Log.net(
                    "RDPServer.retry: sending nul packet in "
                        + (30000 - (currentTime - con.getLastNullPacketTime())));
            }
            con.resend(
                currentTime - resendTimerMS, // resend cutoff time
                currentTime - resendTimeoutMS); // giveup time
          }

          long endTime = System.currentTimeMillis();
          if (Log.loggingNet)
            Log.net(
                "RDPServer.RETRY: endTime=" + endTime + ", elapse(ms)=" + (endTime - startTime));
          Thread.sleep(250);
        } catch (Exception e) {
          Log.exception("RDPServer.RetryThread.run caught exception", e);
        }
      }
    }
Esempio n. 23
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache
  * .mina.core.session.IoSession, java.lang.Throwable)
  */
 @Override
 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
   log.error(cause.getMessage(), cause);
 }
Esempio n. 24
0
  /** returns a list of rdpserversockets */
  Set<DatagramChannel> getActiveChannels() throws InterruptedException, java.io.IOException {
    lock.lock();
    try {
      while (channelMap.isEmpty()) {
        channelMapNotEmpty.await();
      }
    } finally {
      lock.unlock();
    }

    Set<SelectionKey> readyKeys = null;
    do {
      lock.lock();
      try {
        if (!newChannelSet.isEmpty()) {
          if (Log.loggingNet) Log.net("RDPServer.getActiveChannels: newChannelSet is not null");
          Iterator<DatagramChannel> iter = newChannelSet.iterator();
          while (iter.hasNext()) {
            DatagramChannel newDC = iter.next();
            iter.remove();
            newDC.register(selector, SelectionKey.OP_READ);
          }
        }
      } finally {
        lock.unlock();
      }
      int numReady = selector.select(); // this is a blocking call - thread safe
      selectCalls++;
      if (numReady == 0) {
        if (Log.loggingNet) Log.net("RDPServer.getActiveChannels: selector returned 0");
        continue;
      }
      readyKeys = selector.selectedKeys();
      if (Log.loggingNet)
        Log.net(
            "RDPServer.getActiveChannels: called select - # of ready keys = "
                + readyKeys.size()
                + " == "
                + numReady);
    } while (readyKeys == null || readyKeys.isEmpty());

    lock.lock();
    try {
      // get a datagramchannel that is ready
      Set<DatagramChannel> activeChannels = new HashSet<DatagramChannel>();

      Iterator<SelectionKey> iter = readyKeys.iterator();
      while (iter.hasNext()) {
        SelectionKey key = iter.next();
        if (Log.loggingNet)
          Log.net(
              "RDPServer.getActiveChannels: matched selectionkey: "
                  + key
                  + ", isAcceptable="
                  + key.isAcceptable()
                  + ", isReadable="
                  + key.isReadable()
                  + ", isValid="
                  + key.isValid()
                  + ", isWritable="
                  + key.isWritable());
        iter.remove(); // remove from the selected key list

        if (!key.isReadable() || !key.isValid()) {
          Log.error(
              "RDPServer.getActiveChannels: Throwing exception: RDPServer: not readable or invalid");
          throw new MVRuntimeException("RDPServer: not readable or invalid");
        }

        DatagramChannel dc = (DatagramChannel) key.channel();
        activeChannels.add(dc);
      }
      if (Log.loggingNet)
        Log.net(
            "RDPServer.getActiveChannels: returning " + activeChannels.size() + " active channels");
      return activeChannels;
    } finally {
      lock.unlock();
    }
  }
Esempio n. 25
0
  /**
   * we have a packet that belongs to the passed in connection. process the packet for the
   * connection. It returns true if the connection is open and the packet was a data packet
   */
  boolean processExistingConnection(RDPConnection con, RDPPacket packet) {

    if (Log.loggingNet)
      Log.net("RDPServer.processExistingConnection: con state=" + con + ", packet=" + packet);
    packetCounter.add();

    int state = con.getState();
    if (state == RDPConnection.LISTEN) {
      // something is wrong, we shouldn't be here
      // we get to this method after looking in the connections map
      // but all LISTEN connections should be listed direct
      // from serversockets
      Log.error("RDPServer.processExistingConnection: connection shouldnt be in LISTEN state");
      return false;
    }
    if (state == RDPConnection.SYN_SENT) {
      if (!packet.isAck()) {
        Log.warn("got a non-ack packet when we're in SYN_SENT");
        return false;
      }
      if (!packet.isSyn()) {
        Log.warn("got a non-syn packet when we're in SYN_SENT");
        return false;
      }
      if (Log.loggingNet) Log.net("good: got syn-ack packet in syn_sent");

      // make sure its acking our initial segment #
      if (packet.getAckNum() != con.getInitialSendSeqNum()) {
        if (Log.loggingNet) Log.net("syn's ack number does not match initial seq #");
        return false;
      }

      con.setRcvCur(packet.getSeqNum());
      con.setRcvIrs(packet.getSeqNum());
      con.setMaxSendUnacks(packet.getSendUnacks());
      con.setMaxReceiveSegmentSize(packet.getMaxRcvSegmentSize());
      con.setSendUnackd(packet.getAckNum() + 1);

      // ack first before setting state to open
      // otherwise some other thread will get woken up and send data
      // before we send the ack
      if (Log.loggingNet) Log.net("new connection state: " + con);
      RDPPacket replyPacket = new RDPPacket(con);
      con.sendPacketImmediate(replyPacket, false);
      con.setState(RDPConnection.OPEN);
      return false;
    }
    if (state == RDPConnection.SYN_RCVD) {
      if (packet.getSeqNum() <= con.getRcvIrs()) {
        Log.error("seqnum is not above rcv initial seq num");
        return false;
      }
      if (packet.getSeqNum() > (con.getRcvCur() + (con.getRcvMax() * 2))) {
        Log.error("seqnum is too big");
        return false;
      }
      if (packet.isAck()) {
        if (packet.getAckNum() == con.getInitialSendSeqNum()) {
          if (Log.loggingNet) Log.net("got ack for our syn - setting state to open");
          con.setState(RDPConnection.OPEN); // this will notify()

          // call the accept callback
          // first find the serversocket
          DatagramChannel dc = con.getDatagramChannel();
          if (dc == null) {
            throw new MVRuntimeException(
                "RDPServer.processExistingConnection: no datagramchannel for connection that just turned OPEN");
          }
          RDPServerSocket rdpSocket = RDPServer.getRDPSocket(dc);
          if (rdpSocket == null) {
            throw new MVRuntimeException(
                "RDPServer.processExistingConnection: no socket for connection that just turned OPEN");
          }
          ClientConnection.AcceptCallback acceptCB = rdpSocket.getAcceptCallback();
          if (acceptCB != null) {
            acceptCB.acceptConnection(con);
          } else {
            Log.warn("serversocket has no accept callback");
          }
          if (Log.loggingNet)
            Log.net(
                "RDPServer.processExistingConnection: got ACK, removing from unack list: "
                    + packet.getSeqNum());
          con.removeUnackPacket(packet.getSeqNum());
        }
      }
    }
    if (state == RDPConnection.CLOSE_WAIT) {
      // reply with a reset on all packets
      if (!packet.isRst()) {
        RDPPacket rstPacket = RDPPacket.makeRstPacket();
        con.sendPacketImmediate(rstPacket, false);
      }
    }
    if (state == RDPConnection.OPEN) {
      if (packet.isRst()) {
        // the other side wants to close the connection
        // set the state,
        // dont call con.close() since that will send a reset packet
        if (Log.loggingDebug)
          Log.debug("RDPServer.processExistingConnection: got reset packet for con " + con);
        if (con.getState() != RDPConnection.CLOSE_WAIT) {
          con.setState(RDPConnection.CLOSE_WAIT);
          con.setCloseWaitTimer();
          // Only invoke callback when moving into CLOSE_WAIT
          // state.  This prevents two calls to connectionReset.
          Log.net("RDPServer.processExistingConnection: calling reset callback");
          ClientConnection.MessageCallback pcb = con.getCallback();
          pcb.connectionReset(con);
        }

        return false;
      }
      if (packet.isSyn()) {
        // this will close the connection (put into CLOSE_WAIT)
        // send a reset packet and call the connectionReset callback
        Log.error(
            "RDPServer.processExistingConnection: closing connection because we got a syn packet, con="
                + con);
        con.close();
        return false;
      }

      // TODO: shouldnt it be ok for it to have same seq num?
      // if it is a 0 data packet?
      long rcvCur = con.getRcvCur();
      if (packet.getSeqNum() <= rcvCur) {
        if (Log.loggingNet)
          Log.net("RDPServer.processExistingConnection: seqnum too small - acking/not process");
        if (packet.getData() != null) {
          if (Log.loggingNet)
            Log.net(
                "RDPServer.processExistingConnection: sending ack even though seqnum out of range");
          RDPPacket replyPacket = new RDPPacket(con);
          con.sendPacketImmediate(replyPacket, false);
        }
        return false;
      }
      if (packet.getSeqNum() > (rcvCur + (con.getRcvMax() * 2))) {
        Log.error("RDPServer.processExistingConnection: seqnum too big - discarding");
        return false;
      }
      if (packet.isAck()) {
        if (Log.loggingNet)
          Log.net("RDPServer.processExistingConnection: processing ack " + packet.getAckNum());
        // lock for race condition (read then set)
        con.getLock().lock();
        try {
          if (packet.getAckNum() >= con.getSendNextSeqNum()) {
            // acking something we didnt even send yet
            Log.error(
                "RDPServer.processExistingConnection: discarding -- got ack #"
                    + packet.getAckNum()
                    + ", but our next send seqnum is "
                    + con.getSendNextSeqNum()
                    + " -- "
                    + con);
            return false;
          }
          if (con.getSendUnackd() <= packet.getAckNum()) {
            con.setSendUnackd(packet.getAckNum() + 1);
            if (Log.loggingNet)
              Log.net(
                  "RDPServer.processExistingConnection: updated send_unackd num to "
                      + con.getSendUnackd()
                      + " (one greater than packet ack) - "
                      + con);
            con.removeUnackPacketUpTo(packet.getAckNum());
          }
          if (packet.isEak()) {
            List eackList = packet.getEackList();
            Iterator iter = eackList.iterator();
            while (iter.hasNext()) {
              Long seqNum = (Long) iter.next();
              if (Log.loggingNet)
                Log.net("RDPServer.processExistingConnection: got EACK: " + seqNum);
              con.removeUnackPacket(seqNum.longValue());
            }
          }
        } finally {
          con.getLock().unlock();
          if (Log.loggingNet)
            Log.net("RDPServer.processExistingConnection: processed ack " + packet.getAckNum());
        }
      }
      // process the data
      byte[] data = packet.getData();
      if ((data != null) || packet.isNul()) {
        dataCounter.add();

        // lock - since racecondition: we read then set
        con.getLock().lock();
        try {
          rcvCur = con.getRcvCur(); // update rcvCur
          if (Log.loggingNet) Log.net("RDPServer.processExistingConnection: rcvcur is " + rcvCur);

          ClientConnection.MessageCallback pcb = con.getCallback();
          if (pcb == null) {
            Log.warn("RDPServer.processExistingConnection: no packet callback registered");
          }

          // call callback only if we havent seen it already - eackd
          if (!con.hasEack(packet.getSeqNum())) {
            if (con.isSequenced()) {
              // this is a sequential connection,
              // make sure this is the 'next' packet
              // is this the next sequential packet
              if (packet.getSeqNum() == (rcvCur + 1)) {
                // this is the next packet
                if (Log.loggingNet)
                  Log.net(
                      "RDPServer.processExistingConnection: conn is sequenced and received next packet, rcvCur="
                          + rcvCur
                          + ", packet="
                          + packet);
                if ((pcb != null) && (data != null)) {
                  queueForCallbackProcessing(pcb, con, packet);
                }
              } else {
                // not the next packet, place it in queue
                if (Log.loggingNet)
                  Log.net(
                      "RDPServer.processExistingConnection: conn is sequenced, BUT PACKET is OUT OF ORDER: rcvcur="
                          + rcvCur
                          + ", packet="
                          + packet);
                con.addSequencePacket(packet);
              }
            } else {
              if ((pcb != null) && (data != null)) {
                // make sure we havent already processed packet
                queueForCallbackProcessing(pcb, con, packet);
              }
            }
          } else {
            if (Log.loggingNet) Log.net(con.toString() + " already seen this packet");
          }

          // is this the next sequential packet
          if (packet.getSeqNum() == (rcvCur + 1)) {
            con.setRcvCur(rcvCur + 1);
            if (Log.loggingNet)
              Log.net(
                  "RDPServer.processExistingConnection RCVD: incremented last sequenced rcvd: "
                      + (rcvCur + 1));

            // packet in order - dont add to eack
            // Take any additional sequential packets off eack
            long seqNum = rcvCur + 2;
            while (con.removeEack(seqNum)) {
              if (Log.loggingNet)
                Log.net("RDPServer.processExistingConnection: removing/collapsing eack: " + seqNum);
              con.setRcvCur(seqNum++);
            }

            if (con.isSequenced()) {
              rcvCur++; // since we just process the last one
              Log.net(
                  "RDPServer.processExistingConnection: connection is sequenced, processing collapsed packets.");
              // send any saved sequential packets also
              Iterator iter = con.getSequencePackets().iterator();
              while (iter.hasNext()) {
                RDPPacket p = (RDPPacket) iter.next();
                if (Log.loggingNet)
                  Log.net(
                      "rdpserver: stored packet seqnum="
                          + p.getSeqNum()
                          + ", if equal to (rcvcur + 1)="
                          + (rcvCur + 1));
                if (p.getSeqNum() == (rcvCur + 1)) {
                  Log.net(
                      "RDPServer.processExistingConnection: this is the next packet, processing");
                  // this is the next packet - update rcvcur
                  rcvCur++;

                  // process this packet
                  Log.net(
                      "RDPServer.processExistingConnection: processing stored sequential packet "
                          + p);
                  byte[] storedData = p.getData();
                  if (pcb != null && storedData != null) {
                    queueForCallbackProcessing(pcb, con, packet);
                  }
                  iter.remove();
                }
              }
            } else {
              if (Log.loggingNet)
                Log.net("RDPServer.processExistingConnection: connection is not sequenced");
            }
          } else {
            if (Log.loggingNet)
              Log.net(
                  "RDPServer.processExistingConnection: RCVD OUT OF ORDER: packet seq#: "
                      + packet.getSeqNum()
                      + ", but last sequential rcvd packet was: "
                      + con.getRcvCur()
                      + " -- not incrementing counter");
            if (packet.getSeqNum() > rcvCur) {
              // must be at least + 2 larger than rcvCur
              if (Log.loggingNet) Log.net("adding to eack list " + packet);
              con.addEack(packet);
            }
          }
        } finally {
          con.getLock().unlock();
        }
        return true;
      }
    }
    return false;
  }
Esempio n. 26
0
  /**
   * Service.
   *
   * @param o the o
   * @param session the session
   */
  void service(IoBuffer o, IoSession session) {
    try {
      // System.out.println(o.remaining() + "/" + o.capacity());

      session.setAttribute("last", System.currentTimeMillis());

      SimpleIoBuffer in = (SimpleIoBuffer) session.getAttribute("buf");
      if (in == null) {
        in = SimpleIoBuffer.create(4096);
        session.setAttribute("buf", in);
      }
      byte[] data = new byte[o.remaining()];
      o.get(data);
      in.append(data);

      // log.debug("recv: " + data.length + ", " +
      // session.getRemoteAddress());

      while (in.length() > 5) {
        in.mark();
        /**
         * Byte 1: head of the package<br>
         * bit 7-6: "01", indicator of MDC<br>
         * bit 5: encrypt indicator, "0": no; "1": encrypted<br>
         * bit 4: zip indicator, "0": no, "1": ziped<br>
         * bit 0-3: reserved<br>
         * Byte 2-5: length of data<br>
         * Byte[…]: data array<br>
         */
        byte head = in.read();
        /** test the head indicator, if not correct close it */
        if ((head & 0xC0) != 0x40) {
          log.info("flag is not correct! flag:" + head + ",from: " + session.getRemoteAddress());

          session.close(true);
          return;
        }

        int len = in.getInt();

        if (len <= 0 || len > MAX_SIZE) {
          log.error(
              "mdcconnector.Wrong lendth: "
                  + len
                  + "/"
                  + MAX_SIZE
                  + " - "
                  + session.getRemoteAddress());
          session.close(true);
          break;
        }

        if (in.length() < len) {
          in.reset();
          break;
        } else {
          // do it
          // log.info("stub.package.size: " + len);

          byte[] b = new byte[len];
          in.read(b);

          if (TConn.DEBUG) {
            log.debug("recv: " + Bean.toString(b));
          }

          /** test the zip flag */
          if ((head & 0x10) > 0) {
            b = Zip.unzip(b);
          }

          final TConn d = (TConn) session.getAttribute("conn");
          if (d != null) {
            /** test the encrypted flag */
            if ((head & 0x20) > 0) {
              b = DES.decode(b, d.deskey);
            }

            final byte[] bb = b;
            /** test if the packet is for mdc or app */
            new WorkerTask() {

              @Override
              public void onExecute() {
                d.process(bb);
              }
            }.schedule(0);

            session.setAttribute("last", System.currentTimeMillis());
          }
        }
      }
    } catch (Throwable e) {
      log.error("closing stub: " + session.getRemoteAddress(), e);
      session.close(true);
    }
  }