org.ice4j.Transport Java Examples

The following examples show how to use org.ice4j.Transport. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Allocation.java    From turnserver with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new Permission for this Allocation.
 * 
 * @param permission the permission to be added to this allocation.
 */
public void addNewPermission(Permission permission)
{
    TransportAddress peerAddr =
        new TransportAddress(permission.getIpAddress().getAddress(), 0,
            Transport.UDP);
    if (this.permissions.containsKey(peerAddr))
    {
        this.permissions.get(permission.getIpAddress()).refresh();
    }
    else if (!this.canHaveMorePermisions())
    {
        return;
    }
    else
    {
        this.permissions.put(
            permission.getIpAddress(), permission);
        maybeStartPermissionExpireThread();
    }
}
 
Example #2
Source File: Allocation.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * Binds a new Channel to this Allocation. If an existing ChannelBind is found it is refreshed
 * else a new ChannelBind and permission is added.
 * 
 * @param channelBind the channelBind to be added to this allocation.
 * @throws IllegalArgumentException if the channelNo of the channelBind to be added is already
 *         occupied.
 */
public void addChannelBind(ChannelBind channelBind) {
    TransportAddress peerAddr =
            new TransportAddress(channelBind.getPeerAddress().getAddress(), 0, Transport.UDP);
    if (isBadChannelRequest(channelBind)) {
        throw new IllegalArgumentException("400: BAD REQUEST");
    } else if (!channelBindings.containsKey(channelBind.getChannelNo())
            && !peerToChannelMap.containsKey(channelBind.getPeerAddress())) {
        synchronized (this.channelBindings) {
            this.channelBindings.put(channelBind.getChannelNo(), channelBind);
        }
        synchronized (this.peerToChannelMap) {
            this.peerToChannelMap.put(channelBind.getPeerAddress(), channelBind.getChannelNo());
        }
    } else {
        synchronized (this.channelBindings) {
            this.channelBindings.get(channelBind.getChannelNo()).refresh();
        }
    }
    this.addNewPermission(peerAddr);
    maybeStartChannelBindExpireThread();
}
 
Example #3
Source File: IndicationListener.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the message is an Indication message. If yes it then finds the five tuple and
 * corresponding allocation and calls the handleIndication.
 */
@Override
public void handleMessageEvent(StunMessageEvent evt) {
    Message message = evt.getMessage();
    if (Message.isIndicationType(message.getMessageType())) {
        Indication ind = (Indication) message;

        TransportAddress clientAddress = evt.getRemoteAddress();
        TransportAddress serverAddress = evt.getLocalAddress();
        Transport transport = serverAddress.getTransport();
        FiveTuple fiveTuple = new FiveTuple(clientAddress, serverAddress, transport);
        Allocation alloc = turnStack.getServerAllocation(fiveTuple);

        this.handleIndication(ind, alloc);
    }
}
 
Example #4
Source File: TurnTcpAllocationClient.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * Puts the discoverer into an operational state.
 * 
 * @throws IOException if we fail to bind.
 * @throws StunException if the stun4j stack fails start for some reason.
 */
public static void start(Transport protocol) throws IOException, StunException {
    sock = new IceTcpSocketWrapper(tcpSocketToServer);
    logger.debug("Adding an new TCP connection to : " + serverAddress.getHostAddress());

    localAddress = new TransportAddress(InetAddress.getLocalHost(),
            tcpSocketToServer.getLocalPort(), protocol);
    logger.debug("Client adress : " + localAddress);
    logger.debug("Server adress : " + serverAddress);

    ClientChannelDataEventHandler channelDataHandler = new ClientChannelDataEventHandler();
    turnStack = new TurnStack(null, channelDataHandler);
    channelDataHandler.setTurnStack(turnStack);

    turnStack.addSocket(sock);

    requestSender = new BlockingRequestSender(turnStack, localAddress);

    ConnectionAttemptIndicationListener connectionAttemptIndicationListener =
            new ConnectionAttemptIndicationListener(turnStack/* ,requestSender */);
    connectionAttemptIndicationListener.setLocalAddress(localAddress);
    connectionAttemptIndicationListener.start();

    started = true;
}
 
Example #5
Source File: TurnAllocationClient.java    From sctalk with Apache License 2.0 6 votes vote down vote up
public static StunMessageEvent sendCreatePermissionRequest(int peerPort)
        throws IOException, StunException {
    TransportAddress peerAddr =
            new TransportAddress(serverAddress.getAddress(), peerPort, Transport.UDP);
    TransactionID tran = TransactionID.createNewTransactionID();
    logger.debug("Create request for : " + peerAddr);
    Request request = MessageFactory.createCreatePermissionRequest(peerAddr, tran.getBytes());
    StunMessageEvent evt = null;
    logger.debug("Permission tran : " + tran);
    try {
        evt = requestSender.sendRequestAndWaitForResponse(request, serverAddress, tran);
    } catch (StunException ex) {
        // this shouldn't happen since we are the ones that created the
        // request
        logger.debug("Internal Error. Failed to encode a message");
        return null;
    }

    if (evt != null)
        logger.debug("Permission TEST res=" + (int) (evt.getMessage().getMessageType())
                + " - " + evt.getRemoteAddress().getHostAddress());
    else
        logger.debug("NO RESPONSE received to Permission TEST.");

    return evt;
}
 
Example #6
Source File: TurnAllocationClient.java    From sctalk with Apache License 2.0 6 votes vote down vote up
public static void doInteractiveComm() throws IOException, StunException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    logger.debug("Started interaction start typing message");
    String line = br.readLine();
    logger.debug("My first message : " + line);
    while (line != null) {
        byte[] data = line.getBytes();
        TransactionID tran = TransactionID.createNewTransactionID();
        TransportAddress peerAddress =
                new TransportAddress(InetAddress.getLocalHost(), 11000, Transport.UDP);
        Indication ind =
                MessageFactory.createSendIndication(peerAddress, data, tran.getBytes());
        logger.debug("Trying to send message to server");
        turnStack.sendIndication(ind, serverAddress, localAddress);
        logger.debug("message sent");

        logger.debug("Type a new message : ");
        line = br.readLine();
    }
}
 
Example #7
Source File: Allocation.java    From turnserver with Apache License 2.0 5 votes vote down vote up
/**
 * Binds a new Channel to this Allocation.
 * If an existing ChannelBind is found it is refreshed
 * else a new ChannelBind and permission is added.
 * 
 * @param channelBind the channelBind to be added to this allocation.
 * @throws IllegalArgumentException if the channelNo of the channelBind to
 *             be added is already occupied.
 */
public void addChannelBind(ChannelBind channelBind)
{
    TransportAddress peerAddr =
        new TransportAddress(
                channelBind.getPeerAddress().getAddress(),
                0, 
                Transport.UDP);
    if (isBadChannelRequest(channelBind))
    {
        throw new IllegalArgumentException("400: BAD REQUEST");
    }
    else if(!channelBindings.containsKey(channelBind.getChannelNo()) 
           && !peerToChannelMap.containsKey(channelBind.getPeerAddress()))
    {
        synchronized(this.channelBindings)
        {
            this.channelBindings.put(   channelBind.getChannelNo(),
                                        channelBind);
        }
        synchronized(this.peerToChannelMap)
        {
            this.peerToChannelMap.put(
                channelBind.getPeerAddress(), channelBind.getChannelNo());
        }
    }
    else
    {
        synchronized(this.channelBindings)
        {
            this.channelBindings.get(channelBind.getChannelNo()).refresh();
        }
    }
    this.addNewPermission(peerAddr);
    maybeStartChannelBindExpireThread();
}
 
Example #8
Source File: IceTcpEventizedServerSockerWrapper.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * Thread entry point.
 */
@Override
public void run() {
    isRun = true;

    while (isRun) {
        try {
            Socket tcpSocket = serverSocket.accept();

            if (tcpSocket != null) {
                MultiplexingSocket multiplexingSocket = new MultiplexingSocket(tcpSocket);
                component.getParentStream().getParentAgent().getStunStack()
                        .addSocket(new IceTcpSocketWrapper(multiplexingSocket));

                sockets.add(multiplexingSocket);
                String[] serverIpPort = serverSocket.getLocalSocketAddress().toString()
                        .replaceAll("/", "").split(":");
                TransportAddress localAddr =
                        new TransportAddress(InetAddress.getLocalHost(),
                                Integer.parseInt(serverIpPort[1]), Transport.TCP);

                String[] remoteIpPort = tcpSocket.getRemoteSocketAddress().toString()
                        .replaceAll("/", "").split(":");
                TransportAddress remoteAddr = new TransportAddress(remoteIpPort[0],
                        Integer.parseInt(remoteIpPort[1]), Transport.TCP);
                logger.debug("Connection Request from " + remoteAddr + " to " + localAddr);
                TcpConnectEvent event = new TcpConnectEvent(localAddr, remoteAddr);
                IceTcpEventizedServerSockerWrapper.this.fireConnectEvent(event);
            }
        } catch (IOException e) {
            logger.info("Failed to accept TCP socket " + e);
        }
    }
}
 
Example #9
Source File: Allocation.java    From turnserver with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new Permission for this Allocation.
 * 
 * @param peerIP the peer IP address foe which to create this permission to
 *            be added to this allocation.
 */
public void addNewPermission(TransportAddress peerIP)
{
    TransportAddress peerIp =
        new TransportAddress(peerIP.getAddress(), 0, Transport.UDP);
    Permission permission = new Permission(peerIP);
    this.addNewPermission(permission);
}
 
Example #10
Source File: IceClient.java    From IceNAT with Apache License 2.0 5 votes vote down vote up
private IceMediaStream createStream(int rtpPort, String streamName,
                                    Agent agent) throws Throwable
{
    long startTime = System.currentTimeMillis();
    IceMediaStream stream = agent.createMediaStream(streamName);
    // rtp
    Component component = agent.createComponent(stream, Transport.UDP,
                                                rtpPort, rtpPort, rtpPort + 100);

    long endTime = System.currentTimeMillis();
    log.info("Component Name:" + component.getName());
    log.info("RTP Component created in " + (endTime - startTime) + " ms");

    return stream;
}
 
Example #11
Source File: BindingRequestListener.java    From sctalk with Apache License 2.0 5 votes vote down vote up
@Override
public void processRequest(StunMessageEvent evt) throws IllegalArgumentException {

    Message message = evt.getMessage();

    if (message.getMessageType() == Message.BINDING_REQUEST) {
        logger.trace("Received a Binding Request from " + evt.getRemoteAddress());
        TransportAddress mappedAddress = evt.getRemoteAddress();
        // Response response =
        // MessageFactory.createBindingResponse(request,mappedAddress);
        TransportAddress sourceAddress = evt.getLocalAddress();
        TransportAddress changedAddress =
                new TransportAddress("stunserver.org", 3489, Transport.UDP);
        Response response = MessageFactory.create3489BindingResponse(mappedAddress,
                sourceAddress, changedAddress);

        try {
            stunStack.sendResponse(evt.getTransactionID().getBytes(), response,
                    evt.getLocalAddress(), evt.getRemoteAddress());
            logger.trace("Binding Response Sent.");
        } catch (Exception e) {
            logger.warn("Failed to send " + response + " through " + evt.getLocalAddress(), e);
            // try to trigger a 500 response although if this one failed,
            throw new RuntimeException("Failed to send a response", e);
        }
    }
}
 
Example #12
Source File: TurnTcpAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public static void doInteractiveComm() throws IOException, StunException {
    logger.debug("---->Interactve Communication started<---------");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    while ((line = br.readLine()) != null) {
        byte[] data = line.getBytes();
        TransactionID tran = TransactionID.createNewTransactionID();
        TransportAddress peerAddress =
                new TransportAddress(InetAddress.getLocalHost(), 11000, Transport.TCP);
        Indication ind =
                MessageFactory.createSendIndication(peerAddress, data, tran.getBytes());
        turnStack.sendIndication(ind, serverAddress, localAddress);
    }
}
 
Example #13
Source File: TurnTcpAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public static StunMessageEvent sendConnectRequest(int peerPort)
        throws IOException, StunException {

    TransportAddress peerAddr =
            new TransportAddress(serverAddress.getAddress(), peerPort, Transport.TCP);
    TransactionID tran = TransactionID.createNewTransactionID();
    logger.debug("Connect request for : " + peerAddr);
    Request request = MessageFactory.createConnectRequest(peerAddr, tran.getBytes());
    request.setTransactionID(tran.getBytes());
    StunMessageEvent evt = null;
    logger.debug("Connect Req tran : " + tran);
    try {
        evt = requestSender.sendRequestAndWaitForResponse(request, serverAddress, tran);
    } catch (StunException ex) {
        // this shouldn't happen since we are the ones that created the
        // request
        logger.debug("Internal Error. Failed to encode a message");
        return null;
    }

    if (evt != null)
        System.out
                .println("Connect request TEST res=" + (int) (evt.getMessage().getMessageType())
                        + " - " + evt.getRemoteAddress().getHostAddress());
    else
        logger.debug("NO RESPONSE received to Connect Request TEST.");

    return evt;
}
 
Example #14
Source File: TurnTcpAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public static StunMessageEvent sendCreatePermissionRequest(int peerPort)
        throws IOException, StunException {
    
    TransportAddress peerAddr =
            new TransportAddress(serverAddress.getAddress(), peerPort, Transport.TCP);
    TransactionID tran = TransactionID.createNewTransactionID();
    logger.debug("Create request for : " + peerAddr);
    Request request = MessageFactory.createCreatePermissionRequest(peerAddr, tran.getBytes());
    StunMessageEvent evt = null;
    logger.debug("Permission tran : " + tran);
    try {
        evt = requestSender.sendRequestAndWaitForResponse(request, serverAddress, tran);
    } catch (StunException ex) {
        // this shouldn't happen since we are the ones that created the
        // request
        logger.debug("Internal Error. Failed to encode a message");
        return null;
    }

    if (evt != null)
        logger.debug("Permission TEST res=" + (int) (evt.getMessage().getMessageType())
                + " - " + evt.getRemoteAddress().getHostAddress());
    else
        logger.debug("NO RESPONSE received to Permission TEST.");

    return evt;
}
 
Example #15
Source File: TurnTcpAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws StunException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException, StunException, InterruptedException {
    String[] temp = {InetAddress.getLocalHost().toString(), "3478"};
    args = temp;
    Transport protocol = Transport.TCP;

    // uses args as server name and port
    serverAddress = new TransportAddress(InetAddress.getLocalHost(),
            Integer.valueOf(args[1]).intValue(), protocol);

    tcpSocketToServer = new Socket(serverAddress.getHostAddress(), 3478);
    logger.debug("Local port chosen : " + tcpSocketToServer.getLocalPort());

    start(protocol);
    StunMessageEvent evt = null;
    evt = sendAllocationRequest(localAddress, serverAddress);
    evt = sendCreatePermissionRequest(9999);
    // evt = sendCreatePermissionRequest(9999);
    // evt = sendCreatePermissionRequest(11000);
    // evt = sendConnectRequest(9999);

    TransportAddress peerAddr =
            new TransportAddress(InetAddress.getLocalHost(), 11000, protocol);

    Thread.sleep(600 * 1000);

    shutDown();
}
 
Example #16
Source File: TurnAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws StunException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException, StunException, InterruptedException {
    String[] temp = {InetAddress.getLocalHost().getHostAddress(), "3478"};
    // String[] temp = {"176.31.40.85","3478"};
    args = temp;
    Transport protocol = Transport.UDP;

    // uses args as server name and port
    localAddress = new TransportAddress(InetAddress.getLocalHost(), 5678, protocol);
    serverAddress =
            new TransportAddress(args[0], Integer.valueOf(args[1]).intValue(), protocol);
    logger.debug("Client adress : " + localAddress);
    logger.debug("Server adress : " + serverAddress);
    start();
    StunMessageEvent evt = null;
    evt = sendAllocationRequest(localAddress, serverAddress);
    evt = sendCreatePermissionRequest(9999);
    evt = sendCreatePermissionRequest(9999);
    evt = sendCreatePermissionRequest(11000);

    TransportAddress peerAddr =
            new TransportAddress(InetAddress.getLocalHost(), 11000, protocol);

    evt = sendChannelBindRequest((char) 0x4000, peerAddr);
    sendChannelDataMessage();
    logger.debug("Starting interactive communication.");
    doInteractiveComm();
    /*
     * logger.debug("Thread will now sleep."); Thread.sleep(600*1000);
     */
    shutDown();
}
 
Example #17
Source File: Allocation.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new Permission for this Allocation.
 * 
 * @param permission the permission to be added to this allocation.
 */
public void addNewPermission(Permission permission) {
    TransportAddress peerAddr =
            new TransportAddress(permission.getIpAddress().getAddress(), 0, Transport.UDP);
    if (this.permissions.containsKey(peerAddr)) {
        this.permissions.get(permission.getIpAddress()).refresh();
    } else if (!this.canHaveMorePermisions()) {
        return;
    } else {
        this.permissions.put(permission.getIpAddress(), permission);
        maybeStartPermissionExpireThread();
    }
}
 
Example #18
Source File: TurnStack.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new ConnectionId for the specified peerAddress and for the specified allocation.
 * 
 * @param connectionId the connectionId created.
 * @param peerAddress the peerAddress who initiated the TCP connection on the relay address of
 *        the Allocation.
 * @param allocation the allocation corresponding to the relay address on which the connect
 *        request is received.
 */
public void addUnAcknowlededConnectionId(int connectionId, TransportAddress peerAddress,
        Allocation allocation) {
    FiveTuple peerTuple =
            new FiveTuple(peerAddress, allocation.getRelayAddress(), Transport.TCP);
    this.unAcknowledgedConnId.add(connectionId);
    this.peerConnToConnIdMap.put(peerTuple, connectionId);
    this.connIdToAllocMap.put(connectionId, allocation);
    allocation.addPeerTCPConnection(connectionId, peerTuple);
    logger.debug("Adding connectionId-" + connectionId + " for peerTuple-" + peerTuple
            + " at allocation-" + allocation);
}
 
Example #19
Source File: ServerChannelDataEventHandler.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the ChannelDataMessageEvent.
 * 
 * @param evt the ChannelDataMessageEvent to handle/process.
 */
@Override
public void handleMessageEvent(ChannelDataMessageEvent evt) {

    ChannelData channelData = evt.getChannelDataMessage();
    char channelNo = channelData.getChannelNumber();
    byte[] data = channelData.getData();
    logger.trace("Received a ChannelData message for " + (int) channelNo + " , message : "
            + Arrays.toString(data));

    TransportAddress clientAddress = evt.getRemoteAddress();
    TransportAddress serverAddress = evt.getLocalAddress();
    Transport transport = Transport.UDP;
    FiveTuple fiveTuple = new FiveTuple(clientAddress, serverAddress, transport);

    Allocation allocation = this.turnStack.getServerAllocation(fiveTuple);

    if (allocation == null) {
        logger.trace("allocation not found.");
    } else if (!allocation.containsChannel(channelNo)) {
        logger.trace("ChannelNo " + (int) channelNo + " not found in Allocation!");
        return;
    }
    TransportAddress destAddr = allocation.getPeerAddr(channelNo);
    if (destAddr != null) {
        RawMessage message =
                RawMessage.build(data, data.length, destAddr, allocation.getClientAddress());
        try {
            logger.trace("Dispatching a UDP message to " + destAddr + ", data: "
                    + Arrays.toString(message.getBytes()));
            this.turnStack.sendUdpMessage(message, destAddr, allocation.getRelayAddress());
        } catch (StunException e) {
            logger.trace(e.getMessage());
        }
    } else {
        logger.trace("Peer address not found for channel " + (int) channelNo);
    }

}
 
Example #20
Source File: CreatePermissionRequestListener.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@Override
public void processRequest(StunMessageEvent evt) throws IllegalArgumentException {

    logger.trace("Received request " + evt);

    Message message = evt.getMessage();
    if (message.getMessageType() == Message.CREATEPERMISSION_REQUEST) {
        logger.trace("Received create permission request ");
        logger.trace("Event tran : " + evt.getTransactionID());

        XorPeerAddressAttribute xorPeerAddressAttribute =
                (XorPeerAddressAttribute) message.getAttribute(Attribute.XOR_PEER_ADDRESS);
        if (xorPeerAddressAttribute != null) {
            xorPeerAddressAttribute.setAddress(xorPeerAddressAttribute.getAddress(),
                    evt.getTransactionID().getBytes());
        }
        // we should get multiple xor peer address attributes here.
        LifetimeAttribute lifetimeAttribute =
                (LifetimeAttribute) message.getAttribute(Attribute.LIFETIME);

        Response response = null;
        TransportAddress clientAddress = evt.getRemoteAddress();
        TransportAddress serverAddress = evt.getLocalAddress();
        Transport transport = serverAddress.getTransport();
        FiveTuple fiveTuple = new FiveTuple(clientAddress, serverAddress, transport);

        Allocation allocation = this.turnStack.getServerAllocation(fiveTuple);

        Character errorCode = null;
        if (xorPeerAddressAttribute == null || allocation == null) {
            errorCode = ErrorCodeAttribute.BAD_REQUEST;
        } else if (!TurnStack.isIPAllowed(xorPeerAddressAttribute.getAddress())) {
            logger.trace("Peer Address requested " + xorPeerAddressAttribute.getAddress() + " "
                    + TurnStack.isIPAllowed(xorPeerAddressAttribute.getAddress()));
            errorCode = ErrorCodeAttribute.FORBIDDEN;
        } else if (!allocation.canHaveMorePermisions()) {
            errorCode = ErrorCodeAttribute.INSUFFICIENT_CAPACITY;
        }
        if (errorCode != null) {
            logger.trace("Creating error response : " + (int) errorCode);
            response = MessageFactory.createCreatePermissionErrorResponse(errorCode);
        } else {
            logger.trace("Creating success response.");
            TransportAddress peerAddress = xorPeerAddressAttribute.getAddress();
            Permission permission = null;
            if (lifetimeAttribute != null) {
                permission = new Permission(peerAddress, lifetimeAttribute.getLifetime());
            } else {
                permission = new Permission(peerAddress);
            }

            logger.trace("Peer Address requested " + xorPeerAddressAttribute.getAddress() + " "
                    + TurnStack.isIPAllowed(xorPeerAddressAttribute.getAddress()));
            allocation.addNewPermission(permission);
            logger.trace("Added permission to allocation.");
            response = MessageFactory.createCreatePermissionResponse();
        }
        try {
            turnStack.sendResponse(evt.getTransactionID().getBytes(), response,
                    evt.getLocalAddress(), evt.getRemoteAddress());
        } catch (Exception e) {
            logger.warn("Failed to send " + response + " through " + evt.getLocalAddress(), e);
            // try to trigger a 500 response although if this one failed,
            throw new RuntimeException("Failed to send a response", e);
        }
    } else {
        return;
    }
}
 
Example #21
Source File: ChannelBindRequestListener.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@Override
public void processRequest(StunMessageEvent evt) throws IllegalArgumentException {

    logger.trace("Received request {}", evt);

    Message message = evt.getMessage();
    if (message.getMessageType() == Message.CHANNELBIND_REQUEST) {
        logger.trace("Received Channel Bind request ");
        logger.trace("Event tran : " + evt.getTransactionID());

        Response response = null;

        TransportAddress clientAddress = evt.getRemoteAddress();
        TransportAddress serverAddress = evt.getLocalAddress();
        Transport transport = serverAddress.getTransport();
        FiveTuple fiveTuple = new FiveTuple(clientAddress, serverAddress, transport);

        Allocation allocation = this.turnStack.getServerAllocation(fiveTuple);

        ChannelNumberAttribute channelNo =
                (ChannelNumberAttribute) message.getAttribute(Attribute.CHANNEL_NUMBER);
        XorPeerAddressAttribute xorPeerAddress =
                (XorPeerAddressAttribute) message.getAttribute(Attribute.XOR_PEER_ADDRESS);
        if (xorPeerAddress != null) {
            xorPeerAddress.setAddress(xorPeerAddress.getAddress(),
                    evt.getTransactionID().getBytes());
        }

        logger.trace("Adding ChannelBind : " + (int) (channelNo.getChannelNumber()) + ", "
                + xorPeerAddress.getAddress());
        ChannelBind channelBind =
                new ChannelBind(xorPeerAddress.getAddress(), channelNo.getChannelNumber());

        Character errorCode = null;
        if (channelNo == null || xorPeerAddress == null) {
            errorCode = ErrorCodeAttribute.BAD_REQUEST;
        } else if (!ChannelNumberAttribute.isValidRange(channelNo.getChannelNumber())) {
            errorCode = ErrorCodeAttribute.BAD_REQUEST;
        } else if (allocation == null || allocation.isBadChannelRequest(channelBind)) {
            errorCode = ErrorCodeAttribute.BAD_REQUEST;
        } else if (!TurnStack.isIPAllowed(xorPeerAddress.getAddress())) {
            errorCode = ErrorCodeAttribute.FORBIDDEN;
        } else if (!allocation.canHaveMoreChannels()) {
            errorCode = ErrorCodeAttribute.INSUFFICIENT_CAPACITY;
        }

        if (errorCode != null) {
            logger.trace("Creating ChannelBindError response : " + (int) errorCode);
            response = MessageFactory.createChannelBindErrorResponse(errorCode);
        } else {
            logger.trace("Creating ChannelBind sucess response");
            try {
                logger.trace("Adding ChannelBind : " + channelBind);
                allocation.addChannelBind(channelBind);
            } catch (IllegalArgumentException ex) {
                logger.debug(ex.getMessage());
            }
            response = MessageFactory.createChannelBindResponse();
        }

        try {
            turnStack.sendResponse(evt.getTransactionID().getBytes(), response,
                    evt.getLocalAddress(), evt.getRemoteAddress());
        } catch (Exception e) {
            logger.warn("Failed to send " + response + " through " + evt.getLocalAddress(), e);
            // try to trigger a 500 response although if this one failed,
            throw new RuntimeException("Failed to send a response", e);
        }
    } else {
        return;
    }
}
 
Example #22
Source File: RefreshRequestListener.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * (non-Javadoc)
 * 
 * @see org.ice4j.stack.RequestListener#processRequest(org.ice4j.StunMessageEvent)
 */
@Override
public void processRequest(StunMessageEvent evt) throws IllegalArgumentException {

    logger.trace("Received request " + evt);

    Message message = evt.getMessage();
    if (message.getMessageType() == Message.REFRESH_REQUEST) {
        logger.trace("Received refresh request " + evt);

        LifetimeAttribute lifetimeAttribute =
                (LifetimeAttribute) message.getAttribute(Attribute.LIFETIME);

        Response response = null;
        TransportAddress clientAddress = evt.getRemoteAddress();
        TransportAddress serverAddress = evt.getLocalAddress();
        Transport transport = serverAddress.getTransport();
        FiveTuple fiveTuple = new FiveTuple(clientAddress, serverAddress, transport);

        Allocation allocation = this.turnStack.getServerAllocation(fiveTuple);
        if (allocation != null) {
            if (lifetimeAttribute != null) {
                logger.trace(
                        "Refreshing allocation with relay addr " + allocation.getRelayAddress()
                                + " with lifetime " + lifetimeAttribute.getLifetime());
                allocation.refresh(lifetimeAttribute.getLifetime());
                response = MessageFactory.createRefreshResponse((int) allocation.getLifetime());
            } else {
                logger.trace("Refreshing allocation with relay addr "
                        + allocation.getRelayAddress() + " with default lifetime");
                allocation.refresh();
                response = MessageFactory.createRefreshResponse((int) allocation.getLifetime());
            }
        } else {
            logger.trace("Allocation mismatch error");
            response = MessageFactory
                    .createRefreshErrorResponse(ErrorCodeAttribute.ALLOCATION_MISMATCH);
        }
        try {
            turnStack.sendResponse(evt.getTransactionID().getBytes(), response,
                    evt.getLocalAddress(), evt.getRemoteAddress());
        } catch (Exception e) {
            logger.warn("Failed to send " + response + " through " + evt.getLocalAddress(), e);
            // try to trigger a 500 response although if this one failed,
            throw new RuntimeException("Failed to send a response", e);
        }
    } else {
        return;
    }

}
 
Example #23
Source File: Permission.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * @param ipAddress the ipAddress as String of the peer for which to create Permission.
 */
public void setIpAddress(String ipAddress) {
    this.ipAddress = new TransportAddress(ipAddress, 0, Transport.UDP);
}
 
Example #24
Source File: SdpUtils.java    From IceNAT with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the <tt>attribute</tt>.
 *
 * @param attribute the attribute that we need to parse.
 * @param stream the {@link org.ice4j.ice.IceMediaStream} that the candidate is supposed
 * to belong to.
 *
 * @return a newly created {@link org.ice4j.ice.RemoteCandidate} matching the
 * content of the specified <tt>attribute</tt> or <tt>null</tt> if the
 * candidate belonged to a component we don't have.
 */
private static RemoteCandidate parseCandidate(Attribute      attribute,
                                              IceMediaStream stream)
{
    String value = null;

    try{
        value = attribute.getValue();
    }catch (Throwable t){}//can't happen

    StringTokenizer tokenizer = new StringTokenizer(value);

    //XXX add exception handling.
    String foundation = tokenizer.nextToken();
    int componentID = Integer.parseInt( tokenizer.nextToken() );
    Transport transport = Transport.parse(tokenizer.nextToken());
    long priority = Long.parseLong(tokenizer.nextToken());
    String address = tokenizer.nextToken();
    int port = Integer.parseInt(tokenizer.nextToken());

    TransportAddress transAddr
        = new TransportAddress(address, port, transport);

    tokenizer.nextToken(); //skip the "typ" String
    CandidateType type = CandidateType.parse(tokenizer.nextToken());

    Component component = stream.getComponent(componentID);

    if(component == null)
        return null;

    // check if there's a related address property

    RemoteCandidate relatedCandidate = null;
    if (tokenizer.countTokens() >= 4)
    {
        tokenizer.nextToken(); // skip the raddr element
        String relatedAddr = tokenizer.nextToken();
        tokenizer.nextToken(); // skip the rport element
        int relatedPort = Integer.parseInt(tokenizer.nextToken());

        TransportAddress raddr = new TransportAddress(
                        relatedAddr, relatedPort, Transport.UDP);

        relatedCandidate = component.findRemoteCandidate(raddr);
    }

    RemoteCandidate cand = new RemoteCandidate(transAddr, component, type,
                    foundation, priority, relatedCandidate);

    component.addRemoteCandidate(cand);

    return cand;
}
 
Example #25
Source File: FiveTuple.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * @param transport the transport to set.
 */
public void setTransport(Transport transport) {
    this.transport = transport;
}
 
Example #26
Source File: FiveTuple.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * @return the transport protocol used for client server connection.
 */
public Transport getTransport() {
    return transport;
}
 
Example #27
Source File: FiveTuple.java    From sctalk with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new Five tuple Object with given arguments.
 * 
 * @param clientTransportAddress The client's Address to be set
 * @param serverTransportAddress The server's Address to be set
 * @param transport The transport protocol of the client server connection.
 */
public FiveTuple(TransportAddress clientAddress, TransportAddress serverAddress,
        Transport transport) {
    this.clientTransportAddress = clientAddress;
    this.serverTransportAddress = serverAddress;
    this.transport = transport;
}
 
Example #28
Source File: Allocation.java    From sctalk with Apache License 2.0 2 votes vote down vote up
/**
 * Adds a new Permission for this Allocation.
 * 
 * @param peerIP the peer IP address foe which to create this permission to be added to this
 *        allocation.
 */
public void addNewPermission(TransportAddress peerIP) {
    TransportAddress peerIp = new TransportAddress(peerIP.getAddress(), 0, Transport.UDP);
    Permission permission = new Permission(peerIP);
    this.addNewPermission(permission);
}
 
Example #29
Source File: ChannelBind.java    From sctalk with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new ChannelBind object with given lifetime value and UDP as default protocol.
 * 
 * @param peerAddress contains the peer IP address and port no in String format.
 * @param channelNo the channelNo of the ChannelBind.
 * @param lifetime the lifetime of ChannelBind.
 */
public ChannelBind(String peerAddress, char channelNo, long lifetime) {
    this(new TransportAddress(peerAddress, 0, Transport.UDP), channelNo, lifetime);
}