STUN/0000755000175000017500000000000012016431016011551 5ustar paulliupaulliuSTUN/src/0000755000175000017500000000000012016430611012340 5ustar paulliupaulliuSTUN/src/de/0000755000175000017500000000000012016430611012730 5ustar paulliupaulliuSTUN/src/de/javawi/0000755000175000017500000000000012016430611014211 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/0000755000175000017500000000000012016430611015354 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/attribute/0000755000175000017500000000000012016430611017357 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/attribute/ResponseAddress.java0000644000175000017500000000171611154735566023356 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResponseAddress extends MappedResponseChangedSourceAddressReflectedFrom { private static final Logger LOGGER = LoggerFactory.getLogger(ResponseAddress.class); public ResponseAddress() { super(MessageAttribute.MessageAttributeType.ResponseAddress); } public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { ResponseAddress ra = new ResponseAddress(); MappedResponseChangedSourceAddressReflectedFrom.parse(ra, data); LOGGER.debug("Message Attribute: Response Address parsed: " + ra.toString() + "."); return ra; } } STUN/src/de/javawi/jstun/attribute/MessageAttributeInterface.java0000644000175000017500000000206510533067450025327 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; public interface MessageAttributeInterface { public enum MessageAttributeType { MappedAddress, ResponseAddress, ChangeRequest, SourceAddress, ChangedAddress, Username, Password, MessageIntegrity, ErrorCode, UnknownAttribute, ReflectedFrom, Dummy }; final static int MAPPEDADDRESS = 0x0001; final static int RESPONSEADDRESS = 0x0002; final static int CHANGEREQUEST = 0x0003; final static int SOURCEADDRESS = 0x0004; final static int CHANGEDADDRESS = 0x0005; final static int USERNAME = 0x0006; final static int PASSWORD = 0x0007; final static int MESSAGEINTEGRITY = 0x0008; final static int ERRORCODE = 0x0009; final static int UNKNOWNATTRIBUTE = 0x000a; final static int REFLECTEDFROM = 0x000b; final static int DUMMY = 0x0000; }STUN/src/de/javawi/jstun/attribute/Dummy.java0000644000175000017500000000207010534365227021331 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class Dummy extends MessageAttribute { int lengthValue; public Dummy() { super(MessageAttributeType.Dummy); } public void setLengthValue(int length) { this.lengthValue = length; } public byte[] getBytes() throws UtilityException { byte[] result = new byte[lengthValue + 4]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(lengthValue), 0, result, 2, 2); return result; } public static Dummy parse(byte[] data) { Dummy dummy = new Dummy(); dummy.setLengthValue(data.length); return dummy; } } STUN/src/de/javawi/jstun/attribute/MappedResponseChangedSourceAddressReflectedFrom.java0000644000175000017500000000661711107114731031566 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.*; public class MappedResponseChangedSourceAddressReflectedFrom extends MessageAttribute { int port; Address address; /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |x x x x x x x x| Family | Port | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ public MappedResponseChangedSourceAddressReflectedFrom() { super(); try { port = 0; address = new Address("0.0.0.0"); } catch (UtilityException ue) { ue.getMessage(); ue.printStackTrace(); } } public MappedResponseChangedSourceAddressReflectedFrom(MessageAttribute.MessageAttributeType type) { super(type); } public int getPort() { return port; } public Address getAddress() { return address; } public void setPort(int port) throws MessageAttributeException { if ((port > 65536) || (port < 0)) { throw new MessageAttributeException("Port value " + port + " out of range."); } this.port = port; } public void setAddress(Address address) { this.address = address; } public byte[] getBytes() throws UtilityException { byte[] result = new byte[12]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(8), 0, result, 2, 2); // mappedaddress header // family result[5] = Utility.integerToOneByte(0x01); // port System.arraycopy(Utility.integerToTwoBytes(port), 0, result, 6, 2); // address System.arraycopy(address.getBytes(), 0, result, 8, 4); return result; } protected static MappedResponseChangedSourceAddressReflectedFrom parse(MappedResponseChangedSourceAddressReflectedFrom ma, byte[] data) throws MessageAttributeParsingException { try { if (data.length < 8) { throw new MessageAttributeParsingException("Data array too short"); } int family = Utility.oneByteToInteger(data[1]); if (family != 0x01) throw new MessageAttributeParsingException("Family " + family + " is not supported"); byte[] portArray = new byte[2]; System.arraycopy(data, 2, portArray, 0, 2); ma.setPort(Utility.twoBytesToInteger(portArray)); int firstOctet = Utility.oneByteToInteger(data[4]); int secondOctet = Utility.oneByteToInteger(data[5]); int thirdOctet = Utility.oneByteToInteger(data[6]); int fourthOctet = Utility.oneByteToInteger(data[7]); ma.setAddress(new Address(firstOctet, secondOctet, thirdOctet, fourthOctet)); return ma; } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } catch (MessageAttributeException mae) { throw new MessageAttributeParsingException("Port parsing error"); } } public String toString() { return "Address " + address.toString() + ", Port " + port; } }STUN/src/de/javawi/jstun/attribute/SourceAddress.java0000644000175000017500000000167711154735413023015 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SourceAddress extends MappedResponseChangedSourceAddressReflectedFrom { private static final Logger LOGGER = LoggerFactory.getLogger(SourceAddress.class); public SourceAddress() { super(MessageAttribute.MessageAttributeType.SourceAddress); } public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { SourceAddress sa = new SourceAddress(); MappedResponseChangedSourceAddressReflectedFrom.parse(sa, data); LOGGER.debug("Message Attribute: Source Address parsed: " + sa.toString() + "."); return sa; } }STUN/src/de/javawi/jstun/attribute/MessageIntegrity.java0000644000175000017500000000125510532653453023524 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; public class MessageIntegrity extends MessageAttribute { // incomplete message integrity implementation public MessageIntegrity() { super(MessageAttribute.MessageAttributeType.MessageIntegrity); } public byte[] getBytes() { return new byte[0]; } public static MessageIntegrity parse(byte[] data) { return new MessageIntegrity(); } } STUN/src/de/javawi/jstun/attribute/MessageAttributeException.java0000644000175000017500000000102310532653453025361 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; public class MessageAttributeException extends Exception { private static final long serialVersionUID = 3258131345099404850L; public MessageAttributeException(String mesg) { super(mesg); } }STUN/src/de/javawi/jstun/attribute/ErrorCode.java0000644000175000017500000000705410534365227022131 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class ErrorCode extends MessageAttribute { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 0 |Class| Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reason Phrase (variable) .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ int responseCode; String reason; public ErrorCode() { super(MessageAttribute.MessageAttributeType.ErrorCode); } public void setResponseCode(int responseCode) throws MessageAttributeException { switch (responseCode) { case 400: reason = "Bad Request"; break; case 401: reason = "Unauthorized"; break; case 420: reason = "Unkown Attribute"; break; case 430: reason = "Stale Credentials"; break; case 431: reason = "Integrity Check Failure"; break; case 432: reason = "Missing Username"; break; case 433: reason = "Use TLS"; break; case 500: reason = "Server Error"; break; case 600: reason = "Global Failure"; break; default: throw new MessageAttributeException("Response Code is not valid"); } this.responseCode = responseCode; } public int getResponseCode() { return responseCode; } public String getReason() { return reason; } public byte[] getBytes() throws UtilityException { int length = reason.length(); // length adjustment if ((length % 4) != 0) { length += 4 - (length % 4); } // message attribute header length += 4; byte[] result = new byte[length]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(length-4), 0, result, 2, 2); // error code header int classHeader = (int) Math.floor(((double)responseCode)/100); result[6] = Utility.integerToOneByte(classHeader); result[7] = Utility.integerToOneByte(responseCode%100); byte[] reasonArray = reason.getBytes(); System.arraycopy(reasonArray, 0, result, 8, reasonArray.length); return result; } public static ErrorCode parse(byte[] data) throws MessageAttributeParsingException { try { if (data.length < 4) { throw new MessageAttributeParsingException("Data array too short"); } byte classHeaderByte = data[3]; int classHeader = Utility.oneByteToInteger(classHeaderByte); if ((classHeader < 1) || (classHeader > 6)) throw new MessageAttributeParsingException("Class parsing error"); byte numberByte = data[4]; int number = Utility.oneByteToInteger(numberByte); if ((number < 0) || (number > 99)) throw new MessageAttributeParsingException("Number parsing error"); int responseCode = (classHeader * 100) + number; ErrorCode result = new ErrorCode(); result.setResponseCode(responseCode); return result; } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } catch (MessageAttributeException mae) { throw new MessageAttributeParsingException("Parsing error"); } } } STUN/src/de/javawi/jstun/attribute/Username.java0000644000175000017500000000307410534365227022022 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class Username extends MessageAttribute { String username; public Username() { super(MessageAttribute.MessageAttributeType.Username); } public Username(String username) { super(MessageAttribute.MessageAttributeType.Username); setUsername(username); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public byte[] getBytes() throws UtilityException { int length = username.length(); // username header if ((length % 4) != 0) { length += 4 - (length % 4); } // message attribute header length += 4; byte[] result = new byte[length]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(length-4), 0, result, 2, 2); // username header byte[] temp = username.getBytes(); System.arraycopy(temp, 0, result, 4, temp.length); return result; } public static Username parse(byte[] data) { Username result = new Username(); String username = new String(data); result.setUsername(username); return result; } } STUN/src/de/javawi/jstun/attribute/MessageAttributeParsingException.java0000644000175000017500000000106210532653453026710 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; public class MessageAttributeParsingException extends MessageAttributeException { private static final long serialVersionUID = 3258409534426263605L; public MessageAttributeParsingException(String mesg) { super(mesg); } }STUN/src/de/javawi/jstun/attribute/ChangedAddress.java0000644000175000017500000000171011154736007023072 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChangedAddress extends MappedResponseChangedSourceAddressReflectedFrom { private static final Logger LOGGER = LoggerFactory.getLogger(ChangedAddress.class); public ChangedAddress() { super(MessageAttribute.MessageAttributeType.ChangedAddress); } public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { ChangedAddress ca = new ChangedAddress(); MappedResponseChangedSourceAddressReflectedFrom.parse(ca, data); LOGGER.debug("Message Attribute: Changed Address parsed: " + ca.toString() + "."); return ca; } } STUN/src/de/javawi/jstun/attribute/MappedAddress.java0000644000175000017500000000167711154735732022767 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MappedAddress extends MappedResponseChangedSourceAddressReflectedFrom { private static final Logger LOGGER = LoggerFactory.getLogger(MappedAddress.class); public MappedAddress() { super(MessageAttribute.MessageAttributeType.MappedAddress); } public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { MappedAddress ma = new MappedAddress(); MappedResponseChangedSourceAddressReflectedFrom.parse(ma, data); LOGGER.debug("Message Attribute: Mapped Address parsed: " + ma.toString() + "."); return ma; } } STUN/src/de/javawi/jstun/attribute/UnknownAttribute.java0000644000175000017500000000524310534365227023566 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import java.util.*; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class UnknownAttribute extends MessageAttribute { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Attribute 1 Type | Attribute 2 Type | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Attribute 3 Type | Attribute 4 Type ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ Vector unkown = new Vector(); public UnknownAttribute() { super(MessageAttribute.MessageAttributeType.UnknownAttribute); } public void addAttribute(MessageAttributeType attribute) { unkown.add(attribute); } public byte[] getBytes() throws UtilityException { int length = 0; if (unkown.size()%2 == 1) { length = 2 * (unkown.size() + 1) + 4; } else { length = 2 * unkown.size() + 4; } byte[] result = new byte[length]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(length - 4), 0, result, 2, 2); // unkown attribute header Iterator it = unkown.iterator(); while(it.hasNext()) { MessageAttributeType attri = it.next(); System.arraycopy(Utility.integerToTwoBytes(typeToInteger(attri)), 0, result, 4, 2); } // padding if (unkown.size()%2 == 1) { System.arraycopy(Utility.integerToTwoBytes(typeToInteger(unkown.elementAt(1))), 0, result, 4, 2); } return result; } public static UnknownAttribute parse(byte[] data) throws MessageAttributeParsingException { try { UnknownAttribute result = new UnknownAttribute(); if (data.length % 4 != 0) throw new MessageAttributeParsingException("Data array too short"); for (int i = 0; i < data.length; i += 4) { byte[] temp = new byte[4]; System.arraycopy(data, i, temp, 0, 4); long attri = Utility.fourBytesToLong(temp); result.addAttribute(MessageAttribute.intToType(attri)); } return result; } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } } }STUN/src/de/javawi/jstun/attribute/UnknownMessageAttributeException.java0000644000175000017500000000076310532653453026753 0ustar paulliupaulliupackage de.javawi.jstun.attribute; import de.javawi.jstun.attribute.MessageAttributeInterface.MessageAttributeType; public class UnknownMessageAttributeException extends MessageAttributeParsingException { private static final long serialVersionUID = 5375193544145543299L; private MessageAttributeType type; public UnknownMessageAttributeException(String mesg, MessageAttributeType type) { super(mesg); this.type = type; } public MessageAttributeType getType() { return type; } } STUN/src/de/javawi/jstun/attribute/Password.java0000644000175000017500000000307510534365227022046 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class Password extends MessageAttribute { String password; public Password() { super(MessageAttribute.MessageAttributeType.Password); } public Password(String password) { super(MessageAttribute.MessageAttributeType.Password); setPassword(password); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public byte[] getBytes() throws UtilityException { int length = password.length(); // password header if ((length % 4) != 0) { length += 4 - (length % 4); } // message attribute header length += 4; byte[] result = new byte[length]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(length - 4), 0, result, 2, 2); // password header byte[] temp = password.getBytes(); System.arraycopy(temp, 0, result, 4, temp.length); return result; } public static Password parse(byte[] data) { Password result = new Password(); String password = new String(data); result.setPassword(password); return result; } }STUN/src/de/javawi/jstun/attribute/ReflectedFrom.java0000644000175000017500000000172011154735510022753 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReflectedFrom extends MappedResponseChangedSourceAddressReflectedFrom { private static final Logger LOGGER = LoggerFactory.getLogger(ReflectedFrom.class); public ReflectedFrom() { super(MessageAttribute.MessageAttributeType.ReflectedFrom); } public static ReflectedFrom parse(byte[] data) throws MessageAttributeParsingException { ReflectedFrom result = new ReflectedFrom(); MappedResponseChangedSourceAddressReflectedFrom.parse(result, data); LOGGER.debug("Message Attribute: ReflectedFrom parsed: " + result.toString() + "."); return result; } } STUN/src/de/javawi/jstun/attribute/ChangeRequest.java0000644000175000017500000000447310534365227023005 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import de.javawi.jstun.util.*; public class ChangeRequest extends MessageAttribute { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ boolean changeIP = false; boolean changePort = false; public ChangeRequest() { super(MessageAttribute.MessageAttributeType.ChangeRequest); } public boolean isChangeIP() { return changeIP; } public boolean isChangePort() { return changePort; } public void setChangeIP() { changeIP = true; } public void setChangePort() { changePort = true; } public byte[] getBytes() throws UtilityException { byte[] result = new byte[8]; // message attribute header // type System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); // length System.arraycopy(Utility.integerToTwoBytes(4), 0, result, 2, 2); // change request header if (changeIP) result[7] = Utility.integerToOneByte(4); if (changePort) result[7] = Utility.integerToOneByte(2); if (changeIP && changePort) result[7] = Utility.integerToOneByte(6); return result; } public static ChangeRequest parse(byte[] data) throws MessageAttributeParsingException { try { if (data.length < 4) { throw new MessageAttributeParsingException("Data array too short"); } ChangeRequest cr = new ChangeRequest(); int status = Utility.oneByteToInteger(data[3]); switch (status) { case 0: break; case 2: cr.setChangePort(); break; case 4: cr.setChangeIP(); break; case 6: cr.setChangeIP(); cr.setChangePort(); break; default: throw new MessageAttributeParsingException("Status parsing error"); } return cr; } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } } } STUN/src/de/javawi/jstun/attribute/MessageAttribute.java0000644000175000017500000001116111154735650023507 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public abstract class MessageAttribute implements MessageAttributeInterface { private static final Logger LOGGER = LoggerFactory.getLogger(MessageAttribute.class); MessageAttributeType type; public MessageAttribute() { } public MessageAttribute(MessageAttributeType type) { setType(type); } public void setType(MessageAttributeType type) { this.type = type; } public MessageAttribute.MessageAttributeType getType() { return type; } public static int typeToInteger(MessageAttributeType type) { if (type == MessageAttributeType.MappedAddress) return MAPPEDADDRESS; if (type == MessageAttributeType.ResponseAddress) return RESPONSEADDRESS; if (type == MessageAttributeType.ChangeRequest) return CHANGEREQUEST; if (type == MessageAttributeType.SourceAddress) return SOURCEADDRESS; if (type == MessageAttributeType.ChangedAddress) return CHANGEDADDRESS; if (type == MessageAttributeType.Username) return USERNAME; if (type == MessageAttributeType.Password) return PASSWORD; if (type == MessageAttributeType.MessageIntegrity) return MESSAGEINTEGRITY; if (type == MessageAttributeType.ErrorCode) return ERRORCODE; if (type == MessageAttributeType.UnknownAttribute) return UNKNOWNATTRIBUTE; if (type == MessageAttributeType.ReflectedFrom) return REFLECTEDFROM; if (type == MessageAttributeType.Dummy) return DUMMY; return -1; } public static MessageAttributeType intToType(long type) { if (type == MAPPEDADDRESS) return MessageAttributeType.MappedAddress; if (type == RESPONSEADDRESS) return MessageAttributeType.ResponseAddress; if (type == CHANGEREQUEST) return MessageAttributeType.ChangeRequest; if (type == SOURCEADDRESS) return MessageAttributeType.SourceAddress; if (type == CHANGEDADDRESS) return MessageAttributeType.ChangedAddress; if (type == USERNAME) return MessageAttributeType.Username; if (type == PASSWORD) return MessageAttributeType.Password; if (type == MESSAGEINTEGRITY) return MessageAttributeType.MessageIntegrity; if (type == ERRORCODE) return MessageAttributeType.ErrorCode; if (type == UNKNOWNATTRIBUTE) return MessageAttributeType.UnknownAttribute; if (type == REFLECTEDFROM) return MessageAttributeType.ReflectedFrom; if (type == DUMMY) return MessageAttributeType.Dummy; return null; } abstract public byte[] getBytes() throws UtilityException; //abstract public MessageAttribute parse(byte[] data) throws MessageAttributeParsingException; public int getLength() throws UtilityException { int length = getBytes().length; return length; } public static MessageAttribute parseCommonHeader(byte[] data) throws MessageAttributeParsingException { try { byte[] typeArray = new byte[2]; System.arraycopy(data, 0, typeArray, 0, 2); int type = Utility.twoBytesToInteger(typeArray); byte[] lengthArray = new byte[2]; System.arraycopy(data, 2, lengthArray, 0, 2); int lengthValue = Utility.twoBytesToInteger(lengthArray); byte[] valueArray = new byte[lengthValue]; System.arraycopy(data, 4, valueArray, 0, lengthValue); MessageAttribute ma; switch (type) { case MAPPEDADDRESS: ma = MappedAddress.parse(valueArray); break; case RESPONSEADDRESS: ma = ResponseAddress.parse(valueArray); break; case CHANGEREQUEST: ma = ChangeRequest.parse(valueArray); break; case SOURCEADDRESS: ma = SourceAddress.parse(valueArray); break; case CHANGEDADDRESS: ma = ChangedAddress.parse(valueArray); break; case USERNAME: ma = Username.parse(valueArray); break; case PASSWORD: ma = Password.parse(valueArray); break; case MESSAGEINTEGRITY: ma = MessageIntegrity.parse(valueArray); break; case ERRORCODE: ma = ErrorCode.parse(valueArray); break; case UNKNOWNATTRIBUTE: ma = UnknownAttribute.parse(valueArray); break; case REFLECTEDFROM: ma = ReflectedFrom.parse(valueArray); break; default: if (type <= 0x7fff) { throw new UnknownMessageAttributeException("Unkown mandatory message attribute", intToType(type)); } else { LOGGER.debug("MessageAttribute with type " + type + " unkown."); ma = Dummy.parse(valueArray); break; } } return ma; } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } } } STUN/src/de/javawi/jstun/header/0000755000175000017500000000000012016430611016604 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/header/MessageHeader.java0000644000175000017500000001646311154740006022162 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.header; import java.util.Iterator; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.attribute.MessageAttribute; import de.javawi.jstun.attribute.MessageAttributeParsingException; import de.javawi.jstun.util.Utility; import de.javawi.jstun.util.UtilityException; public class MessageHeader implements MessageHeaderInterface { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | STUN Message Type | Message Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * Transaction ID * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ private static final Logger LOGGER = LoggerFactory.getLogger(MessageHeader.class); MessageHeaderType type; byte[] id = new byte[16]; TreeMap ma = new TreeMap(); public MessageHeader() { super(); } public MessageHeader(MessageHeaderType type) { super(); setType(type); } public void setType(MessageHeaderType type) { this.type = type; } public MessageHeaderType getType() { return type; } public static int typeToInteger(MessageHeaderType type) { if (type == MessageHeaderType.BindingRequest) return BINDINGREQUEST; if (type == MessageHeaderType.BindingResponse) return BINDINGRESPONSE; if (type == MessageHeaderType.BindingErrorResponse) return BINDINGERRORRESPONSE; if (type == MessageHeaderType.SharedSecretRequest) return SHAREDSECRETREQUEST; if (type == MessageHeaderType.SharedSecretResponse) return SHAREDSECRETRESPONSE; if (type == MessageHeaderType.SharedSecretErrorResponse) return SHAREDSECRETERRORRESPONSE; return -1; } public void setTransactionID(byte[] id) { System.arraycopy(id, 0, this.id, 0, 16); } public void generateTransactionID() throws UtilityException { System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 0, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 2, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 4, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 6, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 8, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 10, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 12, 2); System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 14, 2); } public byte[] getTransactionID() { byte[] idCopy = new byte[id.length]; System.arraycopy(id, 0, idCopy, 0, id.length); return idCopy; } public boolean equalTransactionID(MessageHeader header) { byte[] idHeader = header.getTransactionID(); if (idHeader.length != 16) return false; if ((idHeader[0] == id[0]) && (idHeader[1] == id[1]) && (idHeader[2] == id[2]) && (idHeader[3] == id[3]) && (idHeader[4] == id[4]) && (idHeader[5] == id[5]) && (idHeader[6] == id[6]) && (idHeader[7] == id[7]) && (idHeader[8] == id[8]) && (idHeader[9] == id[9]) && (idHeader[10] == id[10]) && (idHeader[11] == id[11]) && (idHeader[12] == id[12]) && (idHeader[13] == id[13]) && (idHeader[14] == id[14]) && (idHeader[15] == id[15])) { return true; } else { return false; } } public void addMessageAttribute(MessageAttribute attri) { ma.put(attri.getType(), attri); } public MessageAttribute getMessageAttribute(MessageAttribute.MessageAttributeType type) { return ma.get(type); } public byte[] getBytes() throws UtilityException { int length = 20; Iterator it = ma.keySet().iterator(); while (it.hasNext()) { MessageAttribute attri = ma.get(it.next()); length += attri.getLength(); } // add attribute size + attributes.getSize(); byte[] result = new byte[length]; System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); System.arraycopy(Utility.integerToTwoBytes(length-20), 0, result, 2, 2); System.arraycopy(id, 0, result, 4, 16); // arraycopy of attributes int offset = 20; it = ma.keySet().iterator(); while (it.hasNext()) { MessageAttribute attri = ma.get(it.next()); System.arraycopy(attri.getBytes(), 0, result, offset, attri.getLength()); offset += attri.getLength(); } return result; } public int getLength() throws UtilityException { return getBytes().length; } public void parseAttributes(byte[] data) throws MessageAttributeParsingException { try { byte[] lengthArray = new byte[2]; System.arraycopy(data, 2, lengthArray, 0, 2); int length = Utility.twoBytesToInteger(lengthArray); System.arraycopy(data, 4, id, 0, 16); byte[] cuttedData; int offset = 20; while (length > 0) { cuttedData = new byte[length]; System.arraycopy(data, offset, cuttedData, 0, length); MessageAttribute ma = MessageAttribute.parseCommonHeader(cuttedData); addMessageAttribute(ma); length -= ma.getLength(); offset += ma.getLength(); } } catch (UtilityException ue) { throw new MessageAttributeParsingException("Parsing error"); } } public static MessageHeader parseHeader(byte[] data) throws MessageHeaderParsingException { try { MessageHeader mh = new MessageHeader(); byte[] typeArray = new byte[2]; System.arraycopy(data, 0, typeArray, 0, 2); int type = Utility.twoBytesToInteger(typeArray); switch (type) { case BINDINGREQUEST: mh.setType(MessageHeaderType.BindingRequest); LOGGER.debug("Binding Request received."); break; case BINDINGRESPONSE: mh.setType(MessageHeaderType.BindingResponse); LOGGER.debug("Binding Response received."); break; case BINDINGERRORRESPONSE: mh.setType(MessageHeaderType.BindingErrorResponse); LOGGER.debug("Binding Error Response received."); break; case SHAREDSECRETREQUEST: mh.setType(MessageHeaderType.SharedSecretRequest); LOGGER.debug("Shared Secret Request received."); break; case SHAREDSECRETRESPONSE: mh.setType(MessageHeaderType.SharedSecretResponse); LOGGER.debug("Shared Secret Response received."); break; case SHAREDSECRETERRORRESPONSE: mh.setType(MessageHeaderType.SharedSecretErrorResponse); LOGGER.debug("Shared Secret Error Response received.");break; default: throw new MessageHeaderParsingException("Message type " + type + "is not supported"); } return mh; } catch (UtilityException ue) { throw new MessageHeaderParsingException("Parsing error"); } } }STUN/src/de/javawi/jstun/header/MessageHeaderParsingException.java0000644000175000017500000000104510532653453025363 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.header; public class MessageHeaderParsingException extends MessageHeaderException { private static final long serialVersionUID = 3544393617029607478L; public MessageHeaderParsingException(String mesg) { super(mesg); } }STUN/src/de/javawi/jstun/header/MessageHeaderException.java0000644000175000017500000000101210532653453024031 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.header; public class MessageHeaderException extends Exception { private static final long serialVersionUID = 3689066248944103737L; public MessageHeaderException(String mesg) { super(mesg); } }STUN/src/de/javawi/jstun/header/MessageHeaderInterface.java0000644000175000017500000000146610532653453024010 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.header; public interface MessageHeaderInterface { public enum MessageHeaderType { BindingRequest, BindingResponse, BindingErrorResponse, SharedSecretRequest, SharedSecretResponse, SharedSecretErrorResponse }; final static int BINDINGREQUEST = 0x0001; final static int BINDINGRESPONSE = 0x0101; final static int BINDINGERRORRESPONSE = 0x0111; final static int SHAREDSECRETREQUEST = 0x0002; final static int SHAREDSECRETRESPONSE = 0x0102; final static int SHAREDSECRETERRORRESPONSE = 0x0112; }STUN/src/de/javawi/jstun/util/0000755000175000017500000000000012016430611016331 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/util/Address.java0000644000175000017500000000623610534365227020605 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.util; import java.util.*; import java.net.*; public class Address { int firstOctet; int secondOctet; int thirdOctet; int fourthOctet; public Address(int firstOctet, int secondOctet, int thirdOctet, int fourthOctet) throws UtilityException { if ((firstOctet < 0) || (firstOctet > 255) || (secondOctet < 0) || (secondOctet > 255) || (thirdOctet < 0) || (thirdOctet > 255) || (fourthOctet < 0) || (fourthOctet > 255)) { throw new UtilityException("Address is malformed."); } this.firstOctet = firstOctet; this.secondOctet = secondOctet; this.thirdOctet = thirdOctet; this.fourthOctet = fourthOctet; } public Address(String address) throws UtilityException { StringTokenizer st = new StringTokenizer(address, "."); if (st.countTokens() != 4) { throw new UtilityException("4 octets in address string are required."); } int i = 0; while (st.hasMoreTokens()) { int temp = Integer.parseInt(st.nextToken()); if ((temp < 0) || (temp > 255)) { throw new UtilityException("Address is in incorrect format."); } switch (i) { case 0: firstOctet = temp; ++i; break; case 1: secondOctet = temp; ++i; break; case 2: thirdOctet = temp; ++i; break; case 3: fourthOctet = temp; ++i; break; } } } public Address(byte[] address) throws UtilityException { if (address.length < 4) { throw new UtilityException("4 bytes are required."); } firstOctet = Utility.oneByteToInteger(address[0]); secondOctet = Utility.oneByteToInteger(address[1]); thirdOctet = Utility.oneByteToInteger(address[2]); fourthOctet = Utility.oneByteToInteger(address[3]); } public String toString() { return firstOctet + "." + secondOctet + "." + thirdOctet + "." + fourthOctet; } public byte[] getBytes() throws UtilityException { byte[] result = new byte[4]; result[0] = Utility.integerToOneByte(firstOctet); result[1] = Utility.integerToOneByte(secondOctet); result[2] = Utility.integerToOneByte(thirdOctet); result[3] = Utility.integerToOneByte(fourthOctet); return result; } public InetAddress getInetAddress() throws UtilityException, UnknownHostException { byte[] address = new byte[4]; address[0] = Utility.integerToOneByte(firstOctet); address[1] = Utility.integerToOneByte(secondOctet); address[2] = Utility.integerToOneByte(thirdOctet); address[3] = Utility.integerToOneByte(fourthOctet); return InetAddress.getByAddress(address); } public boolean equals(Object obj) { if (obj == null) return false; try { byte[] data1 = this.getBytes(); byte[] data2 = ((Address) obj).getBytes(); if ((data1[0] == data2[0]) && (data1[1] == data2[1]) && (data1[2] == data2[2]) && (data1[3] == data2[3])) return true; return false; } catch (UtilityException ue) { return false; } } public int hashCode() { return (firstOctet << 24) + (secondOctet << 16) + (thirdOctet << 8) + fourthOctet; } } STUN/src/de/javawi/jstun/util/Utility.java0000644000175000017500000000431110534365227020653 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.util; public class Utility { public static final byte integerToOneByte(int value) throws UtilityException { if ((value > Math.pow(2,15)) || (value < 0)) { throw new UtilityException("Integer value " + value + " is larger than 2^15"); } return (byte)(value & 0xFF); } public static final byte[] integerToTwoBytes(int value) throws UtilityException { byte[] result = new byte[2]; if ((value > Math.pow(2,31)) || (value < 0)) { throw new UtilityException("Integer value " + value + " is larger than 2^31"); } result[0] = (byte)((value >>> 8) & 0xFF); result[1] = (byte)(value & 0xFF); return result; } public static final byte[] integerToFourBytes(int value) throws UtilityException { byte[] result = new byte[4]; if ((value > Math.pow(2,63)) || (value < 0)) { throw new UtilityException("Integer value " + value + " is larger than 2^63"); } result[0] = (byte)((value >>> 24) & 0xFF); result[1] = (byte)((value >>> 16) & 0xFF); result[2] = (byte)((value >>> 8) & 0xFF); result[3] = (byte)(value & 0xFF); return result; } public static final int oneByteToInteger(byte value) throws UtilityException { return (int)value & 0xFF; } public static final int twoBytesToInteger(byte[] value) throws UtilityException { if (value.length < 2) { throw new UtilityException("Byte array too short!"); } int temp0 = value[0] & 0xFF; int temp1 = value[1] & 0xFF; return ((temp0 << 8) + temp1); } public static final long fourBytesToLong(byte[] value) throws UtilityException { if (value.length < 4) { throw new UtilityException("Byte array too short!"); } int temp0 = value[0] & 0xFF; int temp1 = value[1] & 0xFF; int temp2 = value[2] & 0xFF; int temp3 = value[3] & 0xFF; return (((long)temp0 << 24) + (temp1 << 16) + (temp2 << 8) + temp3); } } STUN/src/de/javawi/jstun/util/UtilityException.java0000644000175000017500000000076710532653453022544 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.util; public class UtilityException extends Exception { private static final long serialVersionUID = 3545800974716581680L; UtilityException(String mesg) { super(mesg); } } STUN/src/de/javawi/jstun/test/0000755000175000017500000000000012016430611016333 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/test/DiscoveryTest.java0000644000175000017500000003306611154736775022043 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.attribute.ChangeRequest; import de.javawi.jstun.attribute.ChangedAddress; import de.javawi.jstun.attribute.ErrorCode; import de.javawi.jstun.attribute.MappedAddress; import de.javawi.jstun.attribute.MessageAttribute; import de.javawi.jstun.attribute.MessageAttributeException; import de.javawi.jstun.attribute.MessageAttributeParsingException; import de.javawi.jstun.header.MessageHeader; import de.javawi.jstun.header.MessageHeaderParsingException; import de.javawi.jstun.util.UtilityException; public class DiscoveryTest { private static final Logger LOGGER = LoggerFactory.getLogger(DiscoveryTest.class); InetAddress iaddress; String stunServer; int port; int timeoutInitValue = 300; //ms MappedAddress ma = null; ChangedAddress ca = null; boolean nodeNatted = true; DatagramSocket socketTest1 = null; DiscoveryInfo di = null; public DiscoveryTest(InetAddress iaddress , String stunServer, int port) { super(); this.iaddress = iaddress; this.stunServer = stunServer; this.port = port; } public DiscoveryInfo test() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException{ ma = null; ca = null; nodeNatted = true; socketTest1 = null; di = new DiscoveryInfo(iaddress); if (test1()) { if (test2()) { if (test1Redo()) { test3(); } } } socketTest1.close(); return di; } private boolean test1() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException { int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; while (true) { try { // Test 1 including response socketTest1 = new DatagramSocket(new InetSocketAddress(iaddress, 0)); socketTest1.setReuseAddress(true); socketTest1.connect(InetAddress.getByName(stunServer), port); socketTest1.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); socketTest1.send(send); LOGGER.debug("Test 1: Binding Request sent."); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); socketTest1.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); ca = (ChangedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress); ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return false; } if ((ma == null) || (ca == null)) { di.setError(700, "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry."); LOGGER.debug("Response does not contain a Mapped Address or Changed Address message attribute."); return false; } else { di.setPublicIP(ma.getAddress().getInetAddress()); if ((ma.getPort() == socketTest1.getLocalPort()) && (ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress()))) { LOGGER.debug("Node is not natted."); nodeNatted = false; } else { LOGGER.debug("Node is natted."); } return true; } } catch (SocketTimeoutException ste) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 1: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = (timeSinceFirstTransmission * 2); if (timeoutAddValue > 1600) timeoutAddValue = 1600; timeout = timeoutAddValue; } else { // node is not capable of udp communication LOGGER.debug("Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); di.setBlockedUDP(); LOGGER.debug("Node is not capable of UDP communication."); return false; } } } } private boolean test2() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; while (true) { try { // Test 2 including response DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); sendSocket.connect(InetAddress.getByName(stunServer), port); sendSocket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); changeRequest.setChangeIP(); changeRequest.setChangePort(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); sendSocket.send(send); LOGGER.debug("Test 2: Binding Request sent."); int localPort = sendSocket.getLocalPort(); InetAddress localAddress = sendSocket.getLocalAddress(); sendSocket.close(); DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort()); receiveSocket.setSoTimeout(timeout); MessageHeader receiveMH = new MessageHeader(); while(!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); receiveSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return false; } if (!nodeNatted) { di.setOpenAccess(); LOGGER.debug("Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation)."); } else { di.setFullCone(); LOGGER.debug("Node is behind a full-cone NAT."); } return false; } catch (SocketTimeoutException ste) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 2: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = (timeSinceFirstTransmission * 2); if (timeoutAddValue > 1600) timeoutAddValue = 1600; timeout = timeoutAddValue; } else { LOGGER.debug("Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); if (!nodeNatted) { di.setSymmetricUDPFirewall(); LOGGER.debug("Node is behind a symmetric UDP firewall."); return false; } else { // not is natted // redo test 1 with address and port as offered in the changed-address message attribute return true; } } } } } private boolean test1Redo() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException{ int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; while (true) { // redo test 1 with address and port as offered in the changed-address message attribute try { // Test 1 with changed port and address values socketTest1.connect(ca.getAddress().getInetAddress(), ca.getPort()); socketTest1.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); socketTest1.send(send); LOGGER.debug("Test 1 redo with changed address: Binding Request sent."); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); socketTest1.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } MappedAddress ma2 = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return false; } if (ma2 == null) { di.setError(700, "The server is sending an incomplete response (Mapped Address message attribute is missing). The client should not retry."); LOGGER.debug("Response does not contain a Mapped Address message attribute."); return false; } else { if ((ma.getPort() != ma2.getPort()) || (!(ma.getAddress().getInetAddress().equals(ma2.getAddress().getInetAddress())))) { di.setSymmetric(); LOGGER.debug("Node is behind a symmetric NAT."); return false; } } return true; } catch (SocketTimeoutException ste2) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 1 redo with changed address: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = (timeSinceFirstTransmission * 2); if (timeoutAddValue > 1600) timeoutAddValue = 1600; timeout = timeoutAddValue; } else { LOGGER.debug("Test 1 redo with changed address: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); return false; } } } } private void test3() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; while (true) { try { // Test 3 including response DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); sendSocket.connect(InetAddress.getByName(stunServer), port); sendSocket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); changeRequest.setChangePort(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); sendSocket.send(send); LOGGER.debug("Test 3: Binding Request sent."); int localPort = sendSocket.getLocalPort(); InetAddress localAddress = sendSocket.getLocalAddress(); sendSocket.close(); DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort()); receiveSocket.setSoTimeout(timeout); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); receiveSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return; } if (nodeNatted) { di.setRestrictedCone(); LOGGER.debug("Node is behind a restricted NAT."); return; } } catch (SocketTimeoutException ste) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 3: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = (timeSinceFirstTransmission * 2); if (timeoutAddValue > 1600) timeoutAddValue = 1600; timeout = timeoutAddValue; } else { LOGGER.debug("Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); di.setPortRestrictedCone(); LOGGER.debug("Node is behind a port restricted NAT."); return; } } } } } STUN/src/de/javawi/jstun/test/DiscoveryInfo.java0000644000175000017500000000723110714440646022000 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test; import java.net.*; public class DiscoveryInfo { private InetAddress testIP; private boolean error = false; private int errorResponseCode = 0; private String errorReason; private boolean openAccess = false; private boolean blockedUDP = false; private boolean fullCone = false; private boolean restrictedCone = false; private boolean portRestrictedCone = false; private boolean symmetric = false; private boolean symmetricUDPFirewall = false; private InetAddress publicIP; public DiscoveryInfo(InetAddress testIP) { this.testIP = testIP; } public boolean isError() { return error; } public void setError(int responseCode, String reason) { this.error = true; this.errorResponseCode = responseCode; this.errorReason = reason; } public boolean isOpenAccess() { if (error) return false; return openAccess; } public void setOpenAccess() { this.openAccess = true; } public boolean isBlockedUDP() { if (error) return false; return blockedUDP; } public void setBlockedUDP() { this.blockedUDP = true; } public boolean isFullCone() { if (error) return false; return fullCone; } public void setFullCone() { this.fullCone = true; } public boolean isPortRestrictedCone() { if (error) return false; return portRestrictedCone; } public void setPortRestrictedCone() { this.portRestrictedCone = true; } public boolean isRestrictedCone() { if (error) return false; return restrictedCone; } public void setRestrictedCone() { this.restrictedCone = true; } public boolean isSymmetric() { if (error) return false; return symmetric; } public void setSymmetric() { this.symmetric = true; } public boolean isSymmetricUDPFirewall() { if (error) return false; return symmetricUDPFirewall; } public void setSymmetricUDPFirewall() { this.symmetricUDPFirewall = true; } public InetAddress getPublicIP() { return publicIP; } public InetAddress getLocalIP() { return testIP; } public void setPublicIP(InetAddress publicIP) { this.publicIP = publicIP; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Network interface: "); try { sb.append(NetworkInterface.getByInetAddress(testIP).getName()); } catch (SocketException se) { sb.append("unknown"); } sb.append("\n"); sb.append("Local IP address: "); sb.append(testIP.getHostAddress()); sb.append("\n"); if (error) { sb.append(errorReason + " - Responsecode: " + errorResponseCode); return sb.toString(); } sb.append("Result: "); if (openAccess) sb.append("Open access to the Internet.\n"); if (blockedUDP) sb.append("Firewall blocks UDP.\n"); if (fullCone) sb.append("Full Cone NAT handles connections.\n"); if (restrictedCone) sb.append("Restricted Cone NAT handles connections.\n"); if (portRestrictedCone) sb.append("Port restricted Cone NAT handles connections.\n"); if (symmetric) sb.append("Symmetric Cone NAT handles connections.\n"); if (symmetricUDPFirewall) sb.append ("Symmetric UDP Firewall handles connections.\n"); if (!openAccess && !blockedUDP && !fullCone && !restrictedCone && !portRestrictedCone && !symmetric && !symmetricUDPFirewall) sb.append("unkown\n"); sb.append("Public IP address: "); if (publicIP != null) { sb.append(publicIP.getHostAddress()); } else { sb.append("unknown"); } sb.append("\n"); return sb.toString(); } } STUN/src/de/javawi/jstun/test/BindingLifetimeTest.java0000644000175000017500000001667011154736557023125 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.Timer; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.attribute.ChangeRequest; import de.javawi.jstun.attribute.ErrorCode; import de.javawi.jstun.attribute.MappedAddress; import de.javawi.jstun.attribute.MessageAttribute; import de.javawi.jstun.attribute.MessageAttributeException; import de.javawi.jstun.attribute.MessageAttributeParsingException; import de.javawi.jstun.attribute.ResponseAddress; import de.javawi.jstun.header.MessageHeader; import de.javawi.jstun.header.MessageHeaderParsingException; import de.javawi.jstun.util.UtilityException; public class BindingLifetimeTest { private static final Logger LOGGER = LoggerFactory.getLogger(BindingLifetimeTest.class); String stunServer; int port; int timeout = 300; //ms MappedAddress ma; Timer timer; DatagramSocket initialSocket; // start value for binary search - should be carefully choosen int upperBinarySearchLifetime = 345000; // ms int lowerBinarySearchLifetime = 0; int binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; // lifetime value int lifetime = -1; // -1 means undefined. boolean completed = false; public BindingLifetimeTest(String stunServer, int port) { super(); this.stunServer = stunServer; this.port = port; timer = new Timer(true); } public void test() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { initialSocket = new DatagramSocket(); initialSocket.connect(InetAddress.getByName(stunServer), port); initialSocket.setSoTimeout(timeout); if (bindingCommunicationInitialSocket()) { return; } BindingLifetimeTask task = new BindingLifetimeTask(); timer.schedule(task, binarySearchLifetime); LOGGER.debug("Timer scheduled initially: " + binarySearchLifetime + "."); } private boolean bindingCommunicationInitialSocket() throws UtilityException, IOException, MessageHeaderParsingException, MessageAttributeParsingException { MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port); initialSocket.send(send); LOGGER.debug("Binding Request sent."); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); initialSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { LOGGER.debug("Message header contains an Errorcode message attribute."); return true; } if (ma == null) { LOGGER.debug("Response does not contain a Mapped Address message attribute."); return true; } return false; } public int getLifetime() { return lifetime; } public boolean isCompleted() { return completed; } public void setUpperBinarySearchLifetime(int upperBinarySearchLifetime) { this.upperBinarySearchLifetime = upperBinarySearchLifetime; binarySearchLifetime = (upperBinarySearchLifetime + lowerBinarySearchLifetime) / 2; } class BindingLifetimeTask extends TimerTask { public BindingLifetimeTask() { super(); } public void run() { try { lifetimeQuery(); } catch (Exception e) { LOGGER.debug("Unhandled Exception. BindLifetimeTasks stopped."); e.printStackTrace(); } } public void lifetimeQuery() throws UtilityException, MessageAttributeException, MessageHeaderParsingException, MessageAttributeParsingException, IOException { try { DatagramSocket socket = new DatagramSocket(); socket.connect(InetAddress.getByName(stunServer), port); socket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); ResponseAddress responseAddress = new ResponseAddress(); responseAddress.setAddress(ma.getAddress()); responseAddress.setPort(ma.getPort()); sendMH.addMessageAttribute(changeRequest); sendMH.addMessageAttribute(responseAddress); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port); socket.send(send); LOGGER.debug("Binding Request sent."); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); initialSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { LOGGER.debug("Message header contains errorcode message attribute."); return; } LOGGER.debug("Binding Response received."); if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { LOGGER.debug("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); completed = true; return; } lifetime = binarySearchLifetime; LOGGER.debug("Lifetime update: " + lifetime + "."); lowerBinarySearchLifetime = binarySearchLifetime; binarySearchLifetime = (upperBinarySearchLifetime + lowerBinarySearchLifetime) / 2; if (binarySearchLifetime > 0) { BindingLifetimeTask task = new BindingLifetimeTask(); timer.schedule(task, binarySearchLifetime); LOGGER.debug("Timer scheduled: " + binarySearchLifetime + "."); } else { completed = true; } } catch (SocketTimeoutException ste) { LOGGER.debug("Read operation at query socket timeout."); if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { LOGGER.debug("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); completed = true; return; } upperBinarySearchLifetime = binarySearchLifetime; binarySearchLifetime = (upperBinarySearchLifetime + lowerBinarySearchLifetime) / 2; if (binarySearchLifetime > 0) { if (bindingCommunicationInitialSocket()) { return; } BindingLifetimeTask task = new BindingLifetimeTask(); timer.schedule(task, binarySearchLifetime); LOGGER.debug("Timer scheduled: " + binarySearchLifetime + "."); } else { completed = true; } } } } } STUN/src/de/javawi/jstun/test/demo/0000755000175000017500000000000012016430611017257 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/test/demo/ice/0000755000175000017500000000000012016430611020017 5ustar paulliupaulliuSTUN/src/de/javawi/jstun/test/demo/ice/ICENegociator.java0000644000175000017500000001516711154736324023323 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test.demo.ice; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.attribute.MessageAttributeException; import de.javawi.jstun.header.MessageHeaderParsingException; import de.javawi.jstun.test.DiscoveryInfo; import de.javawi.jstun.test.DiscoveryTest; import de.javawi.jstun.test.demo.ice.Candidate.CandidateType; import de.javawi.jstun.util.Address; import de.javawi.jstun.util.UtilityException; public class ICENegociator { private static final Logger LOGGER = LoggerFactory.getLogger(ICENegociator.class); // type preference must be an integer from 0 (=lowest) to 126 (=highest) (inclusive) private final static int LOCAL_PREFERENCE = 0; private final static int SERVER_REFLEXIVE_PREFERENCE = 42; private final static int PEER_REFLEXIVE_PREFERENCE = 84; private final static int RELAYED_PREFERENCE = 126; // component id private short componentId; private String stunServer = "jstun.javawi.de"; private int stunPort = 3478; // candidates HashSet candidates; public ICENegociator(short componentId) { this.componentId = componentId; candidates = new HashSet(); } public ICENegociator(String stunServer, int stunPort, short componentId) { this.stunServer = stunServer; this.stunPort = stunPort; this.componentId = componentId; candidates = new HashSet(); } /* * This method gathers candidate addresses as described in draft-ietf-mmusic-ice-12.txt Chapter 2.1 * Unfortunately, only the candidates of the direct attached network interfaces and server reflexive * addreses are gathered. So far, no support for relayed candidates is available (because I am not * aware of any STUN relay server). */ public void gatherCandidateAddresses() { try { candidates = new HashSet(); Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration iaddresses = iface.getInetAddresses(); while (iaddresses.hasMoreElements()) { InetAddress iaddress = iaddresses.nextElement(); if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress()) { try { // add host candidate Candidate local = new Candidate(new Address(iaddress.getAddress()), componentId); candidates.add(local); // add server reflexive address DiscoveryTest test = new DiscoveryTest(iaddress, stunServer, stunPort); DiscoveryInfo di = test.test(); if (di.getPublicIP() != null) { Candidate cand = new Candidate(new Address(di.getPublicIP().getAddress()), CandidateType.ServerReflexive, componentId, local); cand.setComponentId(componentId); candidates.add(cand); } } catch (MessageHeaderParsingException mhpe) { LOGGER.debug("MessageHeaderParsingException while gathering candidate addresses."); mhpe.printStackTrace(); } catch (MessageAttributeException mae) { LOGGER.debug("MessageAttributeException while gathering candidate addresses."); mae.printStackTrace(); } catch (UtilityException ue) { LOGGER.debug("UtilityException while gathering candidate addresses."); ue.printStackTrace(); } catch (UnknownHostException uhe) { LOGGER.debug("MessageHeaderParsingException while gathering candidate addresses."); uhe.printStackTrace(); } catch (SocketException se) { LOGGER.debug("SocketException while gathering candidate addresses."); se.printStackTrace(); } catch (IOException ioe) { LOGGER.debug("IOException while gathering candidate addresses."); ioe.printStackTrace(); } } } } } catch (SocketException se) { LOGGER.debug("SocketException while enumatering over the network cards."); se.printStackTrace(); } } public void prioritizeCandidates() { // count number of candidate types int numberLocal = 0; int numberServerReflexive = 0; int numberPeerReflexive = 0; int numberRelayed = 0; // count number of candidates of a particular type Iterator iterCandidates = candidates.iterator(); while (iterCandidates.hasNext()) { Candidate cand = iterCandidates.next(); CandidateType type = cand.getCandidateType(); if (type == CandidateType.Local) numberLocal++; else if (type == CandidateType.ServerReflexive) numberServerReflexive++; else if (type == CandidateType.PeerReflexive) numberPeerReflexive++; else if (type == CandidateType.Relayed) numberRelayed++; } // assign priorities iterCandidates = candidates.iterator(); while (iterCandidates.hasNext()) { int typeValue = 0; int localValue = 0; int componentValue = 0; Candidate cand = iterCandidates.next(); CandidateType type = cand.getCandidateType(); if (type == CandidateType.Local) { typeValue = LOCAL_PREFERENCE; localValue = numberLocal--; } else if (type == CandidateType.ServerReflexive) { typeValue = SERVER_REFLEXIVE_PREFERENCE; localValue = numberServerReflexive--; } else if (type == CandidateType.PeerReflexive) { typeValue = PEER_REFLEXIVE_PREFERENCE; localValue = numberPeerReflexive--; } else if (type == CandidateType.Relayed) { typeValue = RELAYED_PREFERENCE; localValue = numberRelayed--; } componentValue = cand.getComponentId(); int priority = ((2 ^ 24) * typeValue) + ((2 ^ 8) * localValue) + componentValue; cand.setPriority(priority); } } public List getSortedCandidates() { Vector sortedCandidates = new Vector(candidates); Collections.sort(sortedCandidates); return sortedCandidates; } public static void main(String args[]) { ICENegociator cc = new ICENegociator((short) 1); // gather candidates cc.gatherCandidateAddresses(); // priorize candidates cc.prioritizeCandidates(); // get SortedCandidates List sortedCandidates = cc.getSortedCandidates(); // sent sorted candidate addresses to peer over SDP // received sorted candidate addresses of peer over SDP } } STUN/src/de/javawi/jstun/test/demo/ice/Candidate.java0000644000175000017500000000571611117541540022554 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test.demo.ice; import java.net.DatagramSocket; import java.net.SocketException; import java.net.UnknownHostException; import de.javawi.jstun.util.Address; import de.javawi.jstun.util.UtilityException; public class Candidate implements Comparable { // The ieft-mmusic-ice-12 draft is not non-ambigious about the number of types. // Chapter 5.1 defines 3 and 4 types on page 16 and page 17, respectively. public enum CandidateType { Local, ServerReflexive, PeerReflexive, Relayed }; private DatagramSocket socket; private CandidateType type; private short componentId; private int priority; private int foundationId; private Candidate base; private boolean isInUse; public Candidate(Address address, short componentId) throws SocketException, UnknownHostException, UtilityException { this.socket = new DatagramSocket(0, address.getInetAddress()); this.type = CandidateType.Local; this.componentId = componentId; this.priority = 0; this.base = this; this.isInUse = false; } public Candidate(Address address, CandidateType type, short componentId, Candidate base) throws SocketException, UnknownHostException, UtilityException { this.socket = new DatagramSocket(0, address.getInetAddress()); this.type = type; setComponentId(componentId); this.priority = 0; this.base = base; this.isInUse = false; } public void setBase(Candidate base) { this.base = base; } public Candidate getBase() { return base; } public CandidateType getCandidateType() { return type; } public void setComponentId(short componentId) { if ((componentId < 1) || (componentId > 256)) throw new IllegalArgumentException(componentId + " is not between 1 and 256 inclusive."); this.componentId = componentId; } public short getComponentId() { return componentId; } public void setFoundationId(int foundationId) { this.foundationId = foundationId; } public int getFoundationId() { return foundationId; } public void setPriority(int priority) { this.priority = priority; } public int getPriority() { return priority; } public Address getAddress() throws UtilityException { return new Address(socket.getLocalAddress().getAddress()); } public int getPort() { return socket.getLocalPort(); } public void setInUse(boolean isInUse) { this.isInUse = isInUse; } public boolean getInUse() { return isInUse; } public int compareTo(Object arg0) { Candidate cand = (Candidate) arg0; return cand.getPriority() - getPriority(); } public boolean equals(Object o) { if (o == null) return false; if ((((Candidate) o).socket.equals(socket)) && (((Candidate) o).base.equals(base))) return true; return false; } } STUN/src/de/javawi/jstun/test/demo/BindingLifetimeTestDemo.java0000644000175000017500000000261311154737626024644 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test.demo; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.SimpleFormatter; import de.javawi.jstun.test.BindingLifetimeTest; public class BindingLifetimeTestDemo { public static void main(String args[]) { try { Handler fh = new FileHandler("logging.txt"); fh.setFormatter(new SimpleFormatter()); java.util.logging.Logger.getLogger("de.javawi.stun").addHandler(fh); java.util.logging.Logger.getLogger("de.javawi.stun").setLevel(Level.ALL); BindingLifetimeTest test = new BindingLifetimeTest("jstun.javawi.de", 3478); // iphone-stun.freenet.de:3478 // larry.gloo.net:3478 // stun.xten.net:3478 test.test(); boolean continueWhile = true; while(continueWhile) { Thread.sleep(5000); if (test.getLifetime() != -1) { System.out.println("Lifetime: " + test.getLifetime() + " Finished: " + test.isCompleted()); if (test.isCompleted()) continueWhile = false; } } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } STUN/src/de/javawi/jstun/test/demo/StunServer.java0000644000175000017500000002742611154737560022274 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test.demo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Vector; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.SimpleFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.javawi.jstun.attribute.ChangeRequest; import de.javawi.jstun.attribute.ChangedAddress; import de.javawi.jstun.attribute.MappedAddress; import de.javawi.jstun.attribute.MessageAttributeException; import de.javawi.jstun.attribute.MessageAttributeParsingException; import de.javawi.jstun.attribute.ResponseAddress; import de.javawi.jstun.attribute.SourceAddress; import de.javawi.jstun.attribute.UnknownAttribute; import de.javawi.jstun.attribute.UnknownMessageAttributeException; import de.javawi.jstun.attribute.MessageAttributeInterface.MessageAttributeType; import de.javawi.jstun.header.MessageHeader; import de.javawi.jstun.header.MessageHeaderParsingException; import de.javawi.jstun.header.MessageHeaderInterface.MessageHeaderType; import de.javawi.jstun.util.Address; import de.javawi.jstun.util.UtilityException; /* * This class implements a STUN server as described in RFC 3489. * The server requires a machine that is dual-homed to be functional. */ public class StunServer { private static final Logger LOGGER = LoggerFactory.getLogger(StunServer.class); Vector sockets; public StunServer(int primaryPort, InetAddress primary, int secondaryPort, InetAddress secondary) throws SocketException { sockets = new Vector(); sockets.add(new DatagramSocket(primaryPort, primary)); sockets.add(new DatagramSocket(secondaryPort, primary)); sockets.add(new DatagramSocket(primaryPort, secondary)); sockets.add(new DatagramSocket(secondaryPort, secondary)); } public void start() throws SocketException { for (DatagramSocket socket : sockets) { socket.setReceiveBufferSize(2000); StunServerReceiverThread ssrt = new StunServerReceiverThread(socket); ssrt.start(); } } /* * Inner class to handle incoming packets and react accordingly. * I decided not to start a thread for every received Binding Request, because the time * required to receive a Binding Request, parse it, generate a Binding Response and send * it varies only between 2 and 4 milliseconds. This amount of time is small enough so * that no extra thread is needed for incoming Binding Request. */ class StunServerReceiverThread extends Thread { private DatagramSocket receiverSocket; private DatagramSocket changedPort; private DatagramSocket changedIP; private DatagramSocket changedPortIP; StunServerReceiverThread(DatagramSocket datagramSocket) { this.receiverSocket = datagramSocket; for (DatagramSocket socket : sockets) { if ((socket.getLocalPort() != receiverSocket.getLocalPort()) && (socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) changedPort = socket; if ((socket.getLocalPort() == receiverSocket.getLocalPort()) && (!socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) changedIP = socket; if ((socket.getLocalPort() != receiverSocket.getLocalPort()) && (!socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) changedPortIP = socket; } } public void run() { while (true) { try { DatagramPacket receive = new DatagramPacket(new byte[200], 200); receiverSocket.receive(receive); LOGGER.debug(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " datagram received from " + receive.getAddress().getHostAddress() + ":" + receive.getPort()); MessageHeader receiveMH = MessageHeader.parseHeader(receive.getData()); try { receiveMH.parseAttributes(receive.getData()); if (receiveMH.getType() == MessageHeaderType.BindingRequest) { LOGGER.debug(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " Binding Request received from " + receive.getAddress().getHostAddress() + ":" + receive.getPort()); ChangeRequest cr = (ChangeRequest) receiveMH.getMessageAttribute(MessageAttributeType.ChangeRequest); if (cr == null) throw new MessageAttributeException("Message attribute change request is not set."); ResponseAddress ra = (ResponseAddress) receiveMH.getMessageAttribute(MessageAttributeType.ResponseAddress); MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingResponse); sendMH.setTransactionID(receiveMH.getTransactionID()); // Mapped address attribute MappedAddress ma = new MappedAddress(); ma.setAddress(new Address(receive.getAddress().getAddress())); ma.setPort(receive.getPort()); sendMH.addMessageAttribute(ma); // Changed address attribute ChangedAddress ca = new ChangedAddress(); ca.setAddress(new Address(changedPortIP.getLocalAddress().getAddress())); ca.setPort(changedPortIP.getLocalPort()); sendMH.addMessageAttribute(ca); if (cr.isChangePort() && (!cr.isChangeIP())) { LOGGER.debug("Change port received in Change Request attribute"); // Source address attribute SourceAddress sa = new SourceAddress(); sa.setAddress(new Address(changedPort.getLocalAddress().getAddress())); sa.setPort(changedPort.getLocalPort()); sendMH.addMessageAttribute(sa); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); if (ra != null) { send.setPort(ra.getPort()); send.setAddress(ra.getAddress().getInetAddress()); } else { send.setPort(receive.getPort()); send.setAddress(receive.getAddress()); } changedPort.send(send); LOGGER.debug(changedPort.getLocalAddress().getHostAddress() + ":" + changedPort.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); } else if ((!cr.isChangePort()) && cr.isChangeIP()) { LOGGER.debug("Change ip received in Change Request attribute"); // Source address attribute SourceAddress sa = new SourceAddress(); sa.setAddress(new Address(changedIP.getLocalAddress().getAddress())); sa.setPort(changedIP.getLocalPort()); sendMH.addMessageAttribute(sa); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); if (ra != null) { send.setPort(ra.getPort()); send.setAddress(ra.getAddress().getInetAddress()); } else { send.setPort(receive.getPort()); send.setAddress(receive.getAddress()); } changedIP.send(send); LOGGER.debug(changedIP.getLocalAddress().getHostAddress() + ":" + changedIP.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); } else if ((!cr.isChangePort()) && (!cr.isChangeIP())) { LOGGER.debug("Nothing received in Change Request attribute"); // Source address attribute SourceAddress sa = new SourceAddress(); sa.setAddress(new Address(receiverSocket.getLocalAddress().getAddress())); sa.setPort(receiverSocket.getLocalPort()); sendMH.addMessageAttribute(sa); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); if (ra != null) { send.setPort(ra.getPort()); send.setAddress(ra.getAddress().getInetAddress()); } else { send.setPort(receive.getPort()); send.setAddress(receive.getAddress()); } receiverSocket.send(send); LOGGER.debug(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); } else if (cr.isChangePort() && cr.isChangeIP()) { LOGGER.debug("Change port and ip received in Change Request attribute"); // Source address attribute SourceAddress sa = new SourceAddress(); sa.setAddress(new Address(changedPortIP.getLocalAddress().getAddress())); sa.setPort(changedPortIP.getLocalPort()); sendMH.addMessageAttribute(sa); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); if (ra != null) { send.setPort(ra.getPort()); send.setAddress(ra.getAddress().getInetAddress()); } else { send.setPort(receive.getPort()); send.setAddress(receive.getAddress()); } changedPortIP.send(send); LOGGER.debug(changedPortIP.getLocalAddress().getHostAddress() + ":" + changedPortIP.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); } } } catch (UnknownMessageAttributeException umae) { umae.printStackTrace(); // Generate Binding error response MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingErrorResponse); sendMH.setTransactionID(receiveMH.getTransactionID()); // Unknown attributes UnknownAttribute ua = new UnknownAttribute(); ua.addAttribute(umae.getType()); sendMH.addMessageAttribute(ua); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); send.setPort(receive.getPort()); send.setAddress(receive.getAddress()); receiverSocket.send(send); LOGGER.debug(changedPortIP.getLocalAddress().getHostAddress() + ":" + changedPortIP.getLocalPort() + " send Binding Error Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (MessageAttributeParsingException mape) { mape.printStackTrace(); } catch (MessageAttributeException mae) { mae.printStackTrace(); } catch (MessageHeaderParsingException mhpe) { mhpe.printStackTrace(); } catch (UtilityException ue) { ue.printStackTrace(); } catch (ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); } } } } /* * To invoke the STUN server two IP addresses and two ports are required. */ public static void main(String args[]) { try { if (args.length != 4) { System.out.println("usage: java de.javawi.jstun.test.demo.StunServer PORT1 IP1 PORT2 IP2"); System.out.println(); System.out.println(" PORT1 - the first port that should be used by the server"); System.out.println(" IP1 - the first ip address that should be used by the server"); System.out.println(" PORT2 - the second port that should be used by the server"); System.out.println(" IP2 - the second ip address that should be used by the server"); System.exit(0); } Handler fh = new FileHandler("logging_server.txt"); fh.setFormatter(new SimpleFormatter()); java.util.logging.Logger.getLogger("de.javawi.jstun").addHandler(fh); java.util.logging.Logger.getLogger("de.javawi.jstun").setLevel(Level.ALL); StunServer ss = new StunServer(Integer.parseInt(args[0]), InetAddress.getByName(args[1]), Integer.parseInt(args[2]), InetAddress.getByName(args[3])); ss.start(); } catch (SocketException se) { se.printStackTrace(); } catch (UnknownHostException uhe) { uhe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } }STUN/src/de/javawi/jstun/test/demo/DiscoveryTestDemo.java0000644000175000017500000000442211154737541023556 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.test.demo; import java.net.BindException; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import de.javawi.jstun.test.DiscoveryTest; public class DiscoveryTestDemo implements Runnable { InetAddress iaddress; public DiscoveryTestDemo(InetAddress iaddress) { this.iaddress = iaddress; } public void run() { try { DiscoveryTest test = new DiscoveryTest(iaddress, "jstun.javawi.de", 3478); //DiscoveryTest test = new DiscoveryTest(iaddress, "stun.sipgate.net", 10000); // iphone-stun.freenet.de:3478 // larry.gloo.net:3478 // stun.xten.net:3478 // stun.sipgate.net:10000 System.out.println(test.test()); } catch (BindException be) { System.out.println(iaddress.toString() + ": " + be.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void main(String args[]) { try { Handler fh = new FileHandler("logging.txt"); fh.setFormatter(new SimpleFormatter()); Logger.getLogger("de.javawi.jstun").addHandler(fh); Logger.getLogger("de.javawi.jstun").setLevel(Level.ALL); Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration iaddresses = iface.getInetAddresses(); while (iaddresses.hasMoreElements()) { InetAddress iaddress = iaddresses.nextElement(); if (Class.forName("java.net.Inet4Address").isInstance(iaddress)) { if ((!iaddress.isLoopbackAddress()) && (!iaddress.isLinkLocalAddress())) { Thread thread = new Thread(new DiscoveryTestDemo(iaddress)); thread.start(); } } } } } catch (Exception e) { System.out.println(e.getMessage()); } } } STUN/apache-license-2.0.txt0000644000175000017500000002613610532653453015474 0ustar paulliupaulliu Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. STUN/gnu-public-license-2.txt0000644000175000017500000004313310532653453016156 0ustar paulliupaulliu GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. STUN/build/0000755000175000017500000000000012016431020012643 5ustar paulliupaulliuSTUN/build/build.xml0000644000175000017500000001116311154746156014513 0ustar paulliupaulliu
JSTUN ${version}]]>
JSTUN]]>
Copyright © 2009 Thomas King .]]>
STUN/license-slf4j.txt0000644000175000017500000000220710761037530014765 0ustar paulliupaulliuCopyright (c) 2004-2008 QOS.ch All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. STUN/test/0000755000175000017500000000000012016430611012530 5ustar paulliupaulliuSTUN/test/de/0000755000175000017500000000000012016430611013120 5ustar paulliupaulliuSTUN/test/de/javawi/0000755000175000017500000000000012016430611014401 5ustar paulliupaulliuSTUN/test/de/javawi/jstun/0000755000175000017500000000000012016430611015544 5ustar paulliupaulliuSTUN/test/de/javawi/jstun/attribute/0000755000175000017500000000000012016430611017547 5ustar paulliupaulliuSTUN/test/de/javawi/jstun/attribute/MappedAddressTest.java0000644000175000017500000000503210532653453024002 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.attribute; import junit.framework.TestCase; public class MappedAddressTest extends TestCase { MappedAddress ma; byte[] data; public MappedAddressTest(String mesg) { super(mesg); } public void setUp() throws Exception { data = new byte[8]; data[0] = 0; data[1] = 1; data[2] = -8; data[3] = 96; data[4] = 84; data[5] = 56; data[6] = -23; data[7] = 76; ma = (MappedAddress) MappedAddress.parse(data); } /* * Test method for 'de.javawi.jstun.attribute.MappedAddress.MappedAddress()' */ public void testMappedAddress() { new MappedAddress(); } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.getBytes()' */ public void testGetBytes() { try { byte[] result = ma.getBytes(); assertTrue(result[0] == 0); assertTrue(result[1] == 1); assertTrue(result[2] == 0); assertTrue(result[3] == 8); assertTrue(result[4] == data[0]); assertTrue(result[5] == data[1]); assertTrue(result[6] == data[2]); assertTrue(result[7] == data[3]); assertTrue(result[8] == data[4]); assertTrue(result[9] == data[5]); assertTrue(result[10] == data[6]); assertTrue(result[11] == data[7]); } catch (Exception e) { e.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.getPort()' */ public void testGetPort() { assertTrue(ma.getPort() == 63584); } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.getAddress()' */ public void testGetAddress() { try { System.out.println(ma.getAddress().toString()); assertTrue(ma.getAddress().equals(new de.javawi.jstun.util.Address("84.56.233.76"))); } catch (Exception e) { e.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.setPort(int)' */ public void testSetPort() { } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.setAddress(Address)' */ public void testSetAddress() { } /* * Test method for 'de.javawi.jstun.attribute.MappedResponseChangedSourceAddressReflectedFrom.toString()' */ public void testToString() { } } STUN/test/de/javawi/jstun/AllTests.java0000644000175000017500000000125410532653453020160 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun; import junit.framework.Test; import junit.framework.TestSuite; import de.javawi.jstun.util.*; import de.javawi.jstun.attribute.*; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for de.javawi.jstun"); suite.addTestSuite(AddressTest.class); suite.addTestSuite(MappedAddressTest.class); return suite; } } STUN/test/de/javawi/jstun/util/0000755000175000017500000000000012016430611016521 5ustar paulliupaulliuSTUN/test/de/javawi/jstun/util/AddressTest.java0000644000175000017500000000554511144633323021630 0ustar paulliupaulliu/* * This file is part of JSTUN. * * Copyright (c) 2005 Thomas King - All rights * reserved. * * This software is licensed under either the GNU Public License (GPL), * or the Apache 2.0 license. Copies of both license agreements are * included in this distribution. */ package de.javawi.jstun.util; import junit.framework.TestCase; public class AddressTest extends TestCase { Address address; public AddressTest(String mesg) { super(mesg); } protected void setUp() throws Exception { address = new Address("192.168.100.1"); } /* * Test method for 'de.javawi.jstun.util.Address.Address(int, int, int, int)' */ public void testAddressIntIntIntInt() { try { Address comp = new Address(192,168,100,1); assertTrue(address.equals(comp)); } catch (UtilityException ue) { ue.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.Address(String)' */ public void testAddressString() { try { Address comp = new Address("192.168.100.1"); assertTrue(address.equals(comp)); } catch (UtilityException ue) { ue.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.Address(byte[])' */ public void testAddressByteArray() { try { byte[] data = {(byte)192, (byte)168, (byte)100, (byte)1}; Address comp = new Address(data); assertTrue(address.equals(comp)); } catch (UtilityException ue) { ue.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.toString()' */ public void testToString() { try { Address comp = new Address("192.168.100.1"); assertTrue(address.equals(comp)); } catch (UtilityException ue) { ue.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.getBytes()' */ public void testGetBytes() { try { byte[] data = address.getBytes(); assertTrue(data[0] == (byte)192); assertTrue(data[1] == (byte)168); assertTrue(data[2] == (byte)100); assertTrue(data[3] == (byte)1); } catch (UtilityException ue) { ue.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.getInetAddress()' */ public void testGetInetAddress() { try { Address comp = new Address("192.168.100.1"); assertTrue(address.getInetAddress().equals(comp.getInetAddress())); comp = new Address("192.168.100.2"); assertFalse(address.getInetAddress().equals(comp.getInetAddress())); } catch (UtilityException ue) { ue.printStackTrace(); } catch (java.net.UnknownHostException uhe) { uhe.printStackTrace(); } } /* * Test method for 'de.javawi.jstun.util.Address.equals(Object)' */ public void testEqualsObject() { try { Address comp = new Address("192.168.100.1"); assertTrue(address.equals(comp)); comp = new Address("192.168.100.2"); assertFalse(address.equals(comp)); } catch (UtilityException ue) { ue.printStackTrace(); } } }