List of usage examples for io.netty.buffer ByteBuf readUnsignedByte
public abstract short readUnsignedByte();
From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java
License:Apache License
/** * Retrieves a domain name given a buffer containing a DNS packet. If the * name contains a pointer, the position of the buffer will be set to * directly after the pointer's index after the name has been read. * * @param in the byte buffer containing the DNS packet * @return the domain name for an entry/*from w w w .j a va 2 s . c om*/ */ public static String decodeName(ByteBuf in) { int position = -1; int checked = 0; final int end = in.writerIndex(); final int readable = in.readableBytes(); // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems // some servers do not respect this for empty names. So just workaround this and return an empty name in this // case. // // See: // - https://github.com/netty/netty/issues/5014 // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1 if (readable == 0) { return "."; } final StringBuilder name = new StringBuilder(readable << 1); while (in.isReadable()) { final int len = in.readUnsignedByte(); final boolean pointer = (len & 0xc0) == 0xc0; if (pointer) { if (position == -1) { position = in.readerIndex() + 1; } if (!in.isReadable()) { throw new CorruptedFrameException("truncated pointer in a name"); } final int next = (len & 0x3f) << 8 | in.readUnsignedByte(); if (next >= end) { throw new CorruptedFrameException("name has an out-of-range pointer"); } in.readerIndex(next); // check for loops checked += 2; if (checked >= end) { throw new CorruptedFrameException("name contains a loop."); } } else if (len != 0) { if (!in.isReadable(len)) { throw new CorruptedFrameException("truncated label in a name"); } name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.'); in.skipBytes(len); } else { // len == 0 break; } } if (position != -1) { in.readerIndex(position); } if (name.length() == 0) { return "."; } if (name.charAt(name.length() - 1) != '.') { name.append('.'); } return name.toString(); }
From source file:net.epsilony.utils.codec.modbus.func.ReadBooleanRegistersFunction.java
License:Open Source License
@Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { if (data.readableBytes() < getResponseDataLength()) { throw new DecoderException(); }// ww w . j a v a 2 s . co m ReadBooleanRegistersResponse readBooleanRegistersResponse = (ReadBooleanRegistersResponse) response; readBooleanRegistersResponse.setStartingAddress(startingAddress); int dataContentBytes = data.readUnsignedByte(); if (dataContentBytes != getResponseDataLength() - 1) { throw new DecoderException(); } readBooleanRegistersResponse.setQuantityAndAllocate(quantity); int dataByte = 0; int mask = 0; for (int i = 0; i < quantity; i++) { if (i % 8 == 0) { dataByte = data.readUnsignedByte(); mask = 1; } readBooleanRegistersResponse.setValue(i, (mask & dataByte) != 0); mask <<= 1; } }
From source file:net.epsilony.utils.codec.modbus.func.ReadWordRegistersFunction.java
License:Open Source License
@Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { if (data.readableBytes() < getResponseDataLength()) { throw new DecoderException(); }/*from w w w . j a va 2 s . c o m*/ ReadWordRegistersResponse readWordRegistersResponse = (ReadWordRegistersResponse) response; readWordRegistersResponse.setStartingAddress(startingAddress); int dataContentBytes = data.readUnsignedByte(); if (dataContentBytes != getResponseDataLength() - 1) { throw new DecoderException(); } readWordRegistersResponse.setQuantityAndAllocate(quantity); for (int i = 0; i < quantity; i++) { readWordRegistersResponse.setValue(i, data.readUnsignedShort()); } }
From source file:net.epsilony.utils.codec.modbus.handler.ModbusMasterResponseDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 6) { return;//from w w w . ja v a2 s . com } int adupLength = in.getUnsignedShort(in.readerIndex() + 4); int wholeLength = adupLength + 6 + (withCheckSum ? 2 : 0); if (wholeLength > in.readableBytes()) { return; } if (withCheckSum) { checkSum(in, wholeLength); } int transectionId = in.readUnsignedShort(); ModbusRequest request = transectingRequestRetriever.apply(transectionId); if (null == request) { in.readerIndex(in.readerIndex() + wholeLength - 2); out.add(new MissMatchResponse(transectionId)); return; } in.readerIndex(in.readerIndex() + 4); int unitId = in.readUnsignedByte(); if (unitId != request.getUnitId()) { throw new DecoderException(); } int functionCode = in.readUnsignedByte(); if ((functionCode & 0x7F) != request.getFunction().getCode()) { throw new DecoderException(); } ModbusResponse response; if ((functionCode & 0x80) == 0) { switch (functionCode) { case 0x01: { ReadBooleanRegistersResponse bResponse = new ReadBooleanRegistersResponse(); bResponse.setRegisterType(ModbusRegisterType.COIL); response = bResponse; } break; case 0x02: { ReadBooleanRegistersResponse bResponse = new ReadBooleanRegistersResponse(); bResponse.setRegisterType(ModbusRegisterType.DISCRETE_INPUT); response = bResponse; } break; case 0x03: { ReadWordRegistersResponse rResponse = new ReadWordRegistersResponse(); rResponse.setRegisterType(ModbusRegisterType.HOLDING); response = rResponse; break; } case 0x04: { ReadWordRegistersResponse rResponse = new ReadWordRegistersResponse(); rResponse.setRegisterType(ModbusRegisterType.INPUT); response = rResponse; } break; case 0x05: response = new WriteCoilResponse(); break; case 0x06: response = new WriteHoldingResponse(); break; default: throw new UnsupportedFunctionCodeException(); } request.getFunction().decodeResponseData(in, response); } else { ExceptionResponse exResponse = new ExceptionResponse(); exResponse.setFunctionCode(functionCode); exResponse.setExceptionCode(in.readUnsignedByte()); response = exResponse; } response.setTransectionId(transectionId); response.setUnitId(unitId); out.add(response); if (withCheckSum) { in.readerIndex(in.readerIndex() + 2); } }
From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveRequestDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 6) { return;/*from w ww . java2s . c o m*/ } int aduLength = in.getUnsignedShort(in.readerIndex() + 4); int wholeLength = 6 + aduLength + (withCheckSum ? 2 : 0); if (in.readableBytes() < wholeLength) { return; } if (withCheckSum) { checkSum(in, wholeLength); } int transectionId = in.readUnsignedShort(); in.readerIndex(in.readerIndex() + 4); int unitId = in.readUnsignedByte(); int functionCode = in.readUnsignedByte(); ModbusFunction function; switch (functionCode) { case 0x01: function = new ReadBooleanRegistersFunction(ModbusRegisterType.COIL); break; case 0x02: function = new ReadBooleanRegistersFunction(ModbusRegisterType.DISCRETE_INPUT); break; case 0x03: function = new ReadWordRegistersFunction(ModbusRegisterType.HOLDING); break; case 0x04: function = new ReadWordRegistersFunction(ModbusRegisterType.INPUT); break; case 0x05: function = new WriteCoilFunction(); break; case 0x06: function = new WriteHoldingFunction(); break; default: throw new UnsupportedFunctionCodeException(); } try { function.decodeRequestData(in); } catch (Throwable ex) { if (ex instanceof DecoderException) { throw ex; } else { throw new DecoderException(ex); } } ModbusRequest request = new ModbusRequest(transectionId, unitId, function); out.add(request); if (withCheckSum) { in.readerIndex(in.readerIndex() + 2); } }
From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveResponseEncoderTest.java
License:Open Source License
@Test public void test() { ModbusSlaveResponseEncoder encoder = new ModbusSlaveResponseEncoder(); EmbeddedChannel channel = new EmbeddedChannel(encoder); ModbusResponse response = new ModbusResponse() { {//w w w . j a va 2 s.c o m transectionId = 0xabcd; unitId = 0x83; } @Override public void writePduCore(ByteBuf out) { out.writeShort(0xabcd); out.writeShort(0xcdef); transectionId++; } @Override public int getPduCoreLength() { return 4; } @Override public int getFunctionCode() { // TODO Auto-generated method stub return 6; } }; ByteBuf buf = null; for (int i = 0; i < 3; i++) { channel.writeOutbound(response); buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 3, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } encoder.setWithCheckSum(true); for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 6, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes() - 2); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } int calcCrc = Utils.crc(buf, buf.readerIndex() - buffer.length, buffer.length); assertEquals(calcCrc, buf.readUnsignedShort()); assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } }
From source file:net.ieldor.modules.login.LoginManager.java
License:Open Source License
public Player runGameLogin(ByteBuf buffer, Channel channel, ChannelHandlerContext context) { boolean unknownEquals14 = buffer.readUnsignedByte() == 1; int secureBufferSize = buffer.readShort() & 0xFFFF; if (buffer.readableBytes() < secureBufferSize) { channel.write(new LoginResponse(LoginResponse.BAD_SESSION)); //session.getLoginPackets().sendClientPacket(10); return null; }//from w ww . j a v a 2s . c om byte[] secureBytes = new byte[secureBufferSize]; buffer.readBytes(secureBytes); ByteBuf secureBuffer = Unpooled.wrappedBuffer( new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray()); /*byte[] data = new byte[rsaBlockSize]; buffer.readBytes(data, 0, rsaBlockSize); InputStream rsaStream = new InputStream(Utils.cryptRSA(data, Settings.PRIVATE_EXPONENT, Settings.MODULUS));*/ int blockOpcode = secureBuffer.readUnsignedByte(); if (blockOpcode != 10) { channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET)); //session.getLoginPackets().sendClientPacket(10); return null; } int[] xteaKey = new int[4]; for (int key = 0; key < xteaKey.length; key++) { xteaKey[key] = secureBuffer.readInt(); } long vHash = secureBuffer.readLong(); if (vHash != 0L) {// rsa block check, pass part channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET)); return null; } String password = ByteBufUtils.readString(secureBuffer); System.out.println("Password: " + password); //TODO: Implement password encryption //password = Encrypt.encryptSHA1(password); //System.out.println("Found password: "+password); long[] loginSeeds = new long[2]; for (int seed = 0; seed < loginSeeds.length; seed++) { loginSeeds[seed] = secureBuffer.readLong(); } byte[] xteaBlock = new byte[buffer.readableBytes()]; System.out.println("Xtea size: " + xteaBlock.length); buffer.readBytes(xteaBlock); XTEA xtea = new XTEA(xteaKey); xtea.decrypt(xteaBlock, 0, xteaBlock.length); InputStream xteaBuffer = new InputStream(xteaBlock); boolean decodeAsString = xteaBuffer.readByte() == 1; String username = decodeAsString ? xteaBuffer.readString() : Base37Utils.decodeBase37(xteaBuffer.readLong()); System.out.println("Username: " + username); int displayMode = xteaBuffer.readUnsignedByte(); int screenWidth = xteaBuffer.readUnsignedShort(); int screenHeight = xteaBuffer.readUnsignedShort(); int unknown2 = xteaBuffer.readUnsignedByte(); xteaBuffer.skip(24); // 24bytes directly from a file, no idea whats there String settings = xteaBuffer.readString(); int affid = xteaBuffer.readInt(); int indexFiles = xteaBuffer.readByte() & 0xff; int[] crcValues = new int[indexFiles]; int crcCount = xteaBuffer.readUnsignedByte(); for (int i = 1; i < crcValues.length; i++) { crcValues[i] = xteaBuffer.readUnsignedByte(); } @SuppressWarnings("unused") MachineData data = new MachineData(xteaBuffer); xteaBuffer.readInt();// Packet receive count xteaBuffer.readInt();//Unknown xteaBuffer.readInt();//Unknown xteaBuffer.readString();// Some param string (empty) boolean hasAditionalInformation = xteaBuffer.readUnsignedByte() == 1; if (hasAditionalInformation) { xteaBuffer.readString(); // aditionalInformation } boolean hasJagtheora = xteaBuffer.readUnsignedByte() == 1; boolean js = xteaBuffer.readUnsignedByte() == 1; boolean hc = xteaBuffer.readUnsignedByte() == 1; int unknown4 = xteaBuffer.readByte(); int unknown5 = xteaBuffer.readInt(); String serverToken = xteaBuffer.readString(); if (!serverToken.equals(Constants.SERVER_TOKEN)) { System.out.println("Expected token: " + Constants.SERVER_TOKEN + ", found: " + serverToken); channel.write(new LoginResponse(LoginResponse.BAD_SESSION)); return null; } boolean unknown7 = xteaBuffer.readUnsignedByte() == 1; for (int index = 0; index < crcCount; index++) { //int crc = CacheManager.STORE.getIndexes()[index] == null ? -1011863738 : CacheManager.STORE // .getIndexes()[index].getCRC(); int receivedCRC = xteaBuffer.readInt(); /*if (crc != receivedCRC && index < 32) { Logger.log(this, "Invalid CRC at index: "+index+", "+receivedCRC+", "+crc); session.getLoginPackets().sendClientPacket(6); return; }*/ } //TODO: Implement the following checks /*if (Utils.invalidAccountName(username)) { session.getLoginPackets().sendClientPacket(3); return; } if (World.getPlayers().size() >= Settings.PLAYERS_LIMIT - 10) { session.getLoginPackets().sendClientPacket(7); return; } if (World.containsPlayer(username)) { session.getLoginPackets().sendClientPacket(5); return; } if (AntiFlood.getSessionsIP(session.getIP()) > 3) { session.getLoginPackets().sendClientPacket(9); return; }*/ LoadResult result = null; try { result = BinaryPlayerManager.loadPlayer(new LoginHandshakeMessage(username, password, context)); } catch (IOException e) { channel.write(new LoginResponse(LoginResponse.ERROR_PROFILE_LOAD)); return null; } if (result.getReturnCode() != LoginResponse.SUCCESS) { channel.write(new LoginResponse(result.getReturnCode())); return null; } Player player = result.getPlayer(); player.initDisplayName(); channel.write(new LoginConfigData(Constants.NIS_CONFIG, true)); return player; /*player.init(session, username, displayMode, screenWidth, screenHeight, mInformation, new IsaacKeyPair(isaacKeys)); session.getLoginPackets().sendLoginDetails(player); session.setDecoder(3, player); session.setEncoder(2, player);*/ //player.start(); /*Player player; if (!SerializableFilesManager.containsPlayer(username)) player = new Player(password); else { player = SerializableFilesManager.loadPlayer(username); if (player == null) { session.getLoginPackets().sendClientPacket(20); return; } if (!SerializableFilesManager.createBackup(username)) { session.getLoginPackets().sendClientPacket(20); return; } if (!password.equals(player.getPassword())) { session.getLoginPackets().sendClientPacket(3); return; } } if (player.isPermBanned() || player.getBanned() > Utils.currentTimeMillis()) { session.getLoginPackets().sendClientPacket(4); return; }*/ }
From source file:net.ieldor.modules.login.LoginManager.java
License:Open Source License
public void runLobbyLogin(ByteBuf buffer, Channel channel, ChannelHandlerContext context) { int secureBufferSize = buffer.readShort() & 0xFFFF; if (buffer.readableBytes() < secureBufferSize) { channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET)); return;/*from ww w.ja va 2 s . co m*/ } byte[] secureBytes = new byte[secureBufferSize]; buffer.readBytes(secureBytes); ByteBuf secureBuffer = Unpooled.wrappedBuffer( new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray()); int blockOpcode = secureBuffer.readUnsignedByte(); if (blockOpcode != 10) { channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET)); return; } int[] xteaKey = new int[4]; for (int key = 0; key < xteaKey.length; key++) { xteaKey[key] = secureBuffer.readInt(); } long vHash = secureBuffer.readLong(); if (vHash != 0L) { channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET)); return; } String password = ByteBufUtils.readString(secureBuffer); //System.out.println("Found password: "+password); long[] loginSeeds = new long[2]; for (int seed = 0; seed < loginSeeds.length; seed++) { loginSeeds[seed] = secureBuffer.readLong(); } byte[] xteaBlock = new byte[buffer.readableBytes()]; buffer.readBytes(xteaBlock); XTEA xtea = new XTEA(xteaKey); xtea.decrypt(xteaBlock, 0, xteaBlock.length); InputStream xteaBuffer = new InputStream(xteaBlock); boolean decodeAsString = xteaBuffer.readByte() == 1; String username = decodeAsString ? xteaBuffer.readString() : Base37Utils.decodeBase37(xteaBuffer.readLong()); //System.out.println("Found username: "+username); @SuppressWarnings("unused") int gameType = xteaBuffer.readUnsignedByte(); @SuppressWarnings("unused") int languageID = xteaBuffer.readUnsignedByte(); @SuppressWarnings("unused") int displayMode = xteaBuffer.readByte(); @SuppressWarnings("unused") int screenWidth = xteaBuffer.readUnsignedShort();// Client screen width @SuppressWarnings("unused") int screenHeight = xteaBuffer.readUnsignedShort();// Client screen height @SuppressWarnings("unused") int anUnknownByte = xteaBuffer.readByte(); byte[] randomData = new byte[24]; for (int i = 0; i < randomData.length; i++) { randomData[i] = (byte) (xteaBuffer.readByte() & 0xFF); } @SuppressWarnings("unused") String clientSettings = xteaBuffer.readString(); int indexFiles = xteaBuffer.readByte() & 0xff; int[] crcValues = new int[indexFiles]; for (int i = 0; i < crcValues.length; i++) { crcValues[i] = xteaBuffer.readUnsignedByte(); } @SuppressWarnings("unused") MachineData data = new MachineData(xteaBuffer); /*int length = xteaBuffer.readUnsignedByte();byte[] machineData = new byte[length]; for (int data = 0; data < machineData.length; data++) { machineData[data] = (byte) xteaBuffer.readUnsignedByte(); }*/ xteaBuffer.readInt();// Packet receive count xteaBuffer.readString();// Some param string (empty) xteaBuffer.readInt();// Another param (0) xteaBuffer.readInt();// Yet another param (2036537831) String serverToken = xteaBuffer.readString(); if (!serverToken.equals(Constants.SERVER_TOKEN)) { System.out.println("Expected token: " + Constants.SERVER_TOKEN + ", found: " + serverToken); channel.write(new LoginResponse(LoginResponse.BAD_SESSION)); return; } xteaBuffer.readByte();// Final param (2424) LoadResult result = null; try { result = BinaryPlayerManager.loadPlayer(new LoginHandshakeMessage(username, password, context)); } catch (IOException e) { channel.write(new LoginResponse(LoginResponse.ERROR_PROFILE_LOAD)); return; } if (result.getReturnCode() != LoginResponse.SUCCESS) { channel.write(new LoginResponse(result.getReturnCode())); return; } Player player = result.getPlayer(); player.initDisplayName(); int rights = 0; long memberEndDate = 1420073999999L; int memberFlags = 0x1;//0x1 - if members, 0x2 - subscription int lastLoginDay = 0; int recoverySetDay = 4000;//The day on which recovery questions were last set int msgCount = 0; String loginIp = null; int emailStatus = 3;//email status (0 - no email, 1 - pending parental confirmation, 2 - pending confirmation, 3 - registered) String displayName = player.getDisplayName(); WorldData defaultWorld = WorldList.DEFAULT_WORLD; LobbyLoginData lobbyData = new LobbyLoginData(rights, memberEndDate, memberFlags, lastLoginDay, recoverySetDay, msgCount, loginIp, emailStatus, displayName, defaultWorld); channel.write(lobbyData); player.lobbyLogin(context); /*Packet response = encodeLobbyResponse(player); channel.write(new LoginResponse(LoginResponse.SUCCESS, response.getPayload(), response.getLength())); */ }
From source file:net.ieldor.network.codec.buf.PacketBufDecoder.java
License:Open Source License
@Override public Packet decode(ChannelHandlerContext ctx, ByteBuf buf) throws Exception { if (state == State.READ_OPCODE) { if (!buf.readable()) return null; opcode = (buf.readUnsignedByte()) & 0xFF; if (opcode > SIZES.length || opcode < 0) { System.out.println("Invalid opcode received: " + opcode); return null; }// ww w . j av a2 s. co m size = SIZES[opcode]; if (size == -3) { System.out.println("Invalid packet size for: " + opcode); return null; //throw new IOException("Illegal opcode " + opcode + "."); } variable = size == -1; state = variable ? State.READ_SIZE : State.READ_PAYLOAD; } if (state == State.READ_SIZE) { if (!buf.readable()) { return null; } size = buf.readUnsignedByte(); state = State.READ_PAYLOAD; } if (state == State.READ_PAYLOAD) { if (buf.readableBytes() < size) return null; ByteBuf payload = buf.readBytes(size); state = State.READ_OPCODE; //System.out.println("Received packet: opcode="+opcode+", size="+size); return new Packet(opcode, variable ? PacketType.BYTE : PacketType.FIXED, payload); } throw new IllegalStateException(); }
From source file:net.ieldor.network.codec.login.LoginDecoder.java
License:Open Source License
private Object decodeConnectionType(ByteBuf buffer) throws ProtocolException { int loginType = buffer.readUnsignedByte(); if (loginType != 16 && loginType != 18 && loginType != 19) { System.out.println("Invalid login opcode: " + loginType); return new LoginResponse(LoginResponse.BAD_LOGIN_PACKET); // throw new ProtocolException("Invalid login opcode: " + loginType); }//from w w w. ja v a 2 s.c o m currentLoginType = loginType == 19 ? LoginType.LOBBY : LoginType.GAME; loginSize = buffer.readShort() & 0xFFFF; state = LoginState.CLIENT_DETAILS; return decodeClientDetails(buffer); }