org.ice4j.StunException Java Examples

The following examples show how to use org.ice4j.StunException. 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: ConnectionIdAttribute.java    From ice4j with Apache License 2.0 6 votes vote down vote up
/**
* Sets this attribute's fields according to attributeValue array.
* @param attributeValue a binary array containing this attribute's field
*                       values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often
*          offset is equal to the index of the first byte after
*          length)
* @param length the length of the binary array.
* @throws StunException if attributeValue contains invalid data.
*/
@Override
void decodeAttributeBody(byte[] attributeValue, char offset, char length) 
 throws StunException
{
 if(length != DATA_LENGTH)
    {
        throw new StunException("length invalid: " + length);
    }

    connectionIdValue = attributeValue[offset] & 0xff;

    connectionIdValue = connectionIdValue << 8 |
        (attributeValue[offset+1] & 0xff);

    connectionIdValue = connectionIdValue << 8 |
        (attributeValue[offset+2] & 0xff);

    connectionIdValue = connectionIdValue << 8 |
        (attributeValue[offset+3] & 0xff);
}
 
Example #2
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 #3
Source File: RequestedAddressFamilyAttribute.java    From ice4j with Apache License 2.0 6 votes vote down vote up
/**
* Sets this attribute's fields according to attributeValue array.
* @param attributeValue a binary array containing this attribute's field
*                       values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often
*          offset is equal to the index of the first byte after
*          length)
* @param length the length of the binary array.
* @throws StunException if attrubteValue contains invalid data.
*/
@Override
void decodeAttributeBody(byte[] attributeValue, char offset, char length) 
 throws StunException
{
 if(length != DATA_LENGTH)
    {
        throw new StunException("length invalid: " + length);
    }

    family = (char)(attributeValue[offset] & 0xff);

    if(family != IPv4 && family != IPv6)
    {
        // instead throw TurnException
        throw new StunException("invalid family value: " + family);
    }
}
 
Example #4
Source File: SendIndicationListener.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the incoming send indication.
 * 
 * @param ind the indication to handle.
 * @param alloc the allocation associated with message.
 */
@Override
public void handleIndication(Indication ind, Allocation alloc) {
    if (ind.getMessageType() == Message.SEND_INDICATION) {
        logger.trace("Received a Send Indication message.");
        byte[] tran = ind.getTransactionID();
        XorPeerAddressAttribute xorPeerAddress =
                (XorPeerAddressAttribute) ind.getAttribute(Attribute.XOR_PEER_ADDRESS);
        xorPeerAddress.setAddress(xorPeerAddress.getAddress(), tran);
        DataAttribute data = (DataAttribute) ind.getAttribute(Attribute.DATA);
        TransportAddress peerAddr = xorPeerAddress.getAddress();
        if (alloc != null && alloc.isPermitted(peerAddr)) {
            RawMessage udpMessage = RawMessage.build(data.getData(), data.getDataLength(),
                    peerAddr, alloc.getRelayAddress());
            try {
                this.getTurnStack().sendUdpMessage(udpMessage, peerAddr,
                        alloc.getRelayAddress());
                logger.trace("Sent SendIndiaction to " + peerAddr + " from "
                        + alloc.getRelayAddress());
            } catch (StunException e) {
                logger.warn("Unable to send message.");
            }
        }
        // else silently ignore the indication.
    }
}
 
Example #5
Source File: TurnAllocationClient.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() throws IOException, StunException {
    ClientChannelDataEventHandler channelDataHandler = new ClientChannelDataEventHandler();
    turnStack = new TurnStack(null, channelDataHandler);
    channelDataHandler.setTurnStack(turnStack);
    sock = new IceUdpSocketWrapper(new SafeCloseDatagramSocket(localAddress));
    turnStack.addSocket(sock);

    DataIndicationListener dataIndListener = new DataIndicationListener(turnStack);
    dataIndListener.setLocalAddress(localAddress);
    dataIndListener.start();

    requestSender = new BlockingRequestSender(turnStack, localAddress);

    started = true;
}
 
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: 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 #8
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 #9
Source File: TurnServerTransaction.java    From turnserver with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void retransmitResponse()
    throws StunException,
    IOException,
    IllegalArgumentException
{
    super.retransmitResponse();
}
 
Example #10
Source File: PeerTcpConnectEventListner.java    From sctalk with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect(TcpConnectEvent event) {
    logger.trace("Received a connect event src:" + event.getLocalAdress() + ", dest:"
            + event.getRemoteAdress());
    Allocation allocation = this.turnStack.getServerAllocation(event.getLocalAdress());
    if (allocation == null) {
        logger.trace("Allocation not found for relay : " + event.getLocalAdress());
    } else if (allocation.isPermitted(event.getRemoteAdress())) {
        try {
            ConnectionIdAttribute connectionId = AttributeFactory.createConnectionIdAttribute();
            logger.trace("Created ConnectionId - " + connectionId.getConnectionIdValue()
                    + " for client " + allocation.getClientAddress());
            TransactionID tranID = TransactionID.createNewTransactionID();
            Indication connectionAttemptIndication = MessageFactory
                    .createConnectionAttemptIndication(connectionId.getConnectionIdValue(),
                            event.getRemoteAdress(), tranID.getBytes());
            this.turnStack.addUnAcknowlededConnectionId(connectionId.getConnectionIdValue(),
                    event.getRemoteAdress(), allocation);
            logger.trace("Sending Connection Attempt Indication.");
            this.turnStack.sendIndication(connectionAttemptIndication,
                    allocation.getClientAddress(), allocation.getServerAddress());
        } catch (StunException e) {
            logger.trace("Unable to send Connection Attempt Indiacation to "
                    + allocation.getClientAddress());
        }
    } else {
        logger.trace("permission not installed for - " + event.getRemoteAdress());
    }
    // this.turnStack.add
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: TurnAllocationClient.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public static void sendChannelDataMessage() throws StunException, IOException {
    byte[] message = {0xa, 0xb};
    ChannelData channelData = new ChannelData();
    channelData.setChannelNumber((char) 0x4000);
    channelData.setData(message);
    turnStack.sendChannelData(channelData, serverAddress, localAddress);
    logger.debug("ChannelData message sent.");
}
 
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: TurnAllocationClient.java    From sctalk with Apache License 2.0 4 votes vote down vote up
public static StunMessageEvent sendChannelBindRequest(char channelNo,
        TransportAddress peerAddress) throws IOException, StunException {
    logger.debug("ChannelBind request for : " + peerAddress + " on " + (int) channelNo);
    TransactionID tran = TransactionID.createNewTransactionID();
    Request request =
            MessageFactory.createChannelBindRequest(channelNo, peerAddress, tran.getBytes());
    char cNo = ((ChannelNumberAttribute) (request.getAttribute(Attribute.CHANNEL_NUMBER)))
            .getChannelNumber();
    TransportAddress pAddr =
            ((XorPeerAddressAttribute) (request.getAttribute(Attribute.XOR_PEER_ADDRESS)))
                    .getAddress();

    XorMappedAddressAttribute mappedAddr =
            AttributeFactory.createXorMappedAddressAttribute(localAddress, tran.getBytes());
    // mappedAddr.setAddress(mappedAddr.getAddress(), tran.getBytes());
    logger.debug(">" + mappedAddr.getAddress());
    request.putAttribute(mappedAddr);
    logger.debug("input mappedAddress : " + mappedAddr.getAddress());

    XorMappedAddressAttribute retMapAddr =
            (XorMappedAddressAttribute) (request.getAttribute(Attribute.XOR_MAPPED_ADDRESS));

    TransportAddress mAddr = (retMapAddr).getAddress();
    logger.debug("output mappedAddress : " + mAddr.getHostAddress());

    logger.debug("Retrived ChannelBind request is : " + pAddr + " on " + (int) cNo);

    StunMessageEvent evt = null;
    logger.debug("ChannelBind 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("ChannelBind TEST res=" + evt.getRemoteAddress().toString() + " - "
                + evt.getRemoteAddress().getHostAddress());
    else
        logger.debug("NO RESPONSE received to ChannelBind TEST.");

    return evt;
}
 
Example #18
Source File: TurnServerTransaction.java    From sctalk with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void retransmitResponse()
        throws StunException, IOException, IllegalArgumentException {
    super.retransmitResponse();
}
 
Example #19
Source File: PeerTcpConnectEventListner.java    From turnserver with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnect(TcpConnectEvent event)
{
    logger.setLevel(Level.FINEST);
    logger.finest("Received a connect event src:" + event.getLocalAdress()
        + ", dest:" + event.getRemoteAdress());
    Allocation allocation =
        this.turnStack.getServerAllocation(event.getLocalAdress());
    if (allocation == null)
    {
        logger.finest("Allocation not found for relay : "
            + event.getLocalAdress());
    }
    else if (allocation.isPermitted(event.getRemoteAdress()))
    {
        try
        {
            ConnectionIdAttribute connectionId =
                AttributeFactory.createConnectionIdAttribute();
            logger.finest("Created ConnectionId - "
                + connectionId.getConnectionIdValue() + " for client "
                + allocation.getClientAddress());
            TransactionID tranID = TransactionID.createNewTransactionID();
            Indication connectionAttemptIndication =
                MessageFactory.createConnectionAttemptIndication(
                    connectionId.getConnectionIdValue(),
                    event.getRemoteAdress(), tranID.getBytes());
            this.turnStack.addUnAcknowlededConnectionId(
                connectionId.getConnectionIdValue(),
                event.getRemoteAdress(), allocation);
            logger.finest("Sending Connection Attempt Indication.");
            this.turnStack.sendIndication(
                connectionAttemptIndication, allocation.getClientAddress(),
                allocation.getServerAddress());
        }
        catch (StunException e)
        {
            logger
                .finest("Unable to send Connection Attempt Indiacation to "
                    + allocation.getClientAddress());
        }
    }
    else
    {
        logger.finest("permission not installed for - "
            + event.getRemoteAdress());
    }
    // this.turnStack.add
}