Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.48 KB | None | 0 0
  1. package org.rse.network.codec;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.Channel;
  6. import io.netty.channel.ChannelFutureListener;
  7. import io.netty.channel.ChannelHandlerContext;
  8. import io.netty.handler.codec.ByteToMessageDecoder;
  9.  
  10. import java.util.HashMap;
  11. import java.util.LinkedList;
  12. import java.util.List;
  13. import java.util.concurrent.ExecutorService;
  14. import java.util.concurrent.Executors;
  15.  
  16. import org.rse.Server;
  17. import org.rse.cache.Cache;
  18. import org.rse.model.World;
  19. import org.rse.model.mortals.players.Player;
  20. import org.rse.model.mortals.players.PlayerFile;
  21. import org.rse.network.packets.PacketSender;
  22. import org.rse.network.stream.InStream;
  23. import org.rse.network.stream.OutStream;
  24. import org.rse.utility.BCrypt;
  25. import org.rse.utility.MACAddress;
  26. import org.rse.utility.Misc;
  27. import org.rse.utility.Redis;
  28. import org.rse.utility.Redis.AuthResult;
  29. import org.rse.utility.XTEADecipher;
  30.  
  31. public final class RS2Decoder extends ByteToMessageDecoder {
  32.  
  33.     private static final int[] UPDATE_KEYS = { 1476, 78700, 44880, 39771, 358716, 44375, 0, 16497, 9063, 303354,
  34.             859711, 234014, 386188, 471057, 1010288, 22171, 27556, 17864, 1244, 18569, 1728, 119, 934587, 1985065,
  35.             4930, 3481 };
  36.  
  37.     private static final byte HANDSHAKE_STAGE = 0, UPDATE_STAGE = 1, LOGIN_STAGE = 2;
  38.  
  39.     private static final HashMap<String, Boolean> loginRequests = new HashMap<>();
  40.  
  41.     private LinkedList<String> requests = new LinkedList<String>();
  42.     private static ExecutorService updateService = Executors.newCachedThreadPool();
  43.  
  44.     private byte stage = HANDSHAKE_STAGE;
  45.  
  46.     private int encryptionValue;
  47.  
  48.     private void decodeFileRequest(Channel channel, ByteBuf buffer, boolean priority) {
  49.         int idx = buffer.readByte() & 0xff;
  50.         int fileId = buffer.readInt();
  51.         if (idx != 255) {
  52.             if (Cache.STORE.getIndexes().length <= idx || Cache.STORE.getIndexes()[idx] == null
  53.                     || !Cache.STORE.getIndexes()[idx].archiveExists(fileId)) {
  54.                 return;
  55.             }
  56.         } else if (fileId != 255) {
  57.             if (Cache.STORE.getIndexes().length <= fileId || Cache.STORE.getIndexes()[fileId] == null) {
  58.                 return;
  59.             }
  60.         }
  61.         if (priority) {
  62.             updateService.submit(() -> writeCacheFile(channel, idx, fileId, true));
  63.         } else {
  64.             requests.add(idx + "," + fileId);
  65.         }
  66.         while (requests.size() > 0) {
  67.             String[] request = requests.removeFirst().split(",");
  68.             writeCacheFile(channel, Integer.parseInt(request[0]), Integer.parseInt(request[1]), false);
  69.         }
  70.     }
  71.  
  72.     private void writeCacheFile(Channel channel, int idx, int fileId, boolean priority) {
  73.         if (idx == 255 && fileId == 255) {
  74.             channel.writeAndFlush(Cache.getVersionTable());
  75.         } else {
  76.             channel.writeAndFlush(Cache.getFileBuffer(idx, fileId, priority, encryptionValue));
  77.         }
  78.     }
  79.  
  80.     private static void sendReturnCode(Channel channel, int returnCode) {
  81.         ByteBuf buffer = Unpooled.buffer(1);
  82.         buffer.writeByte(returnCode);
  83.         channel.writeAndFlush(buffer).addListener(ChannelFutureListener.CLOSE);
  84.     }
  85.  
  86.     @Override
  87.     protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
  88.         Channel channel = ctx.channel();
  89.         if (!channel.isOpen() || !buffer.isReadable()) {
  90.             /**
  91.              * Nothing should be decoded.
  92.              */
  93.             return;
  94.         }
  95.         int opcode;
  96.         switch (stage) {
  97.         case HANDSHAKE_STAGE:
  98.             stage = -1;
  99.             opcode = buffer.readByte() & 0xff;
  100.             switch (opcode) {
  101.             case 14:
  102.                 if (buffer.readableBytes() != 0) {
  103.                     /**
  104.                      * Invalid buffer size.
  105.                      */
  106.                     System.err.println("[RS2Decoder] 1 - Invalid buffer size! " + buffer.readableBytes());
  107.                     channel.close();
  108.                     return;
  109.                 }
  110.                 ByteBuf loginRequestBuffer = Unpooled.buffer(1);
  111.                 loginRequestBuffer.writeByte(0);
  112.                 channel.writeAndFlush(loginRequestBuffer);
  113.                 stage = LOGIN_STAGE;
  114.                 break;
  115.             case 15:
  116.                 int size = buffer.readByte() & 0xff;
  117.                 if (buffer.readableBytes() < size) {
  118.                     /**
  119.                      * Invalid buffer size.
  120.                      */
  121.                     System.err.println("[RS2Decoder] 2 - Invalid buffer size!" + " " + buffer.readableBytes());
  122.                     channel.close();
  123.                     return;
  124.                 }
  125.                 if (buffer.readableBytes() < 4) {
  126.                     /**
  127.                      * Invalid buffer size.
  128.                      */
  129.                     System.err.println("[RS2Decoder] 3 - Invalid buffer size!" + " " + buffer.readableBytes());
  130.                     channel.close();
  131.                     return;
  132.                 }
  133.                 int clientVersion = buffer.readInt();
  134.                 int subVersion = buffer.readInt();
  135.                 if (clientVersion != Server.VERSION || subVersion != Server.SUB_VERSION) {
  136.                     /**
  137.                      * Invalid client version.
  138.                      */
  139.                     sendReturnCode(channel, 6);
  140.                     return;
  141.                 }
  142.                 byte[] bytes = new byte[buffer.readableBytes()];
  143.                 buffer.readBytes(bytes);
  144.                 InStream in = new InStream(bytes);
  145.                 if (!in.readString().equals(Server.CLIENT_VERIFICATION)) {
  146.                     /**
  147.                      * Invalid client verification
  148.                      */
  149.                     sendReturnCode(channel, 6);
  150.                     return;
  151.                 }
  152.                 ByteBuf updateRequestBuffer = Unpooled.buffer(109);
  153.                 updateRequestBuffer.writeByte(0);
  154.                 for (int key : UPDATE_KEYS) {
  155.                     updateRequestBuffer.writeInt(key);
  156.                 }
  157.                 channel.writeAndFlush(updateRequestBuffer);
  158.                 stage = UPDATE_STAGE;
  159.                 return;
  160.             case 28:
  161.                 // Account Creation
  162.                 channel.close();
  163.                 return;
  164.             case 29:
  165.                 // Facebook login
  166.                 channel.close();
  167.                 return;
  168.             default:
  169.                 /**
  170.                  * Unsupported handshake request.
  171.                  */
  172.                 System.err.println("[RS2Decoder] 4 - Invalid request: " + opcode + "!");
  173.                 channel.close();
  174.                 return;
  175.             }
  176.             return;
  177.         case UPDATE_STAGE:
  178.             while (buffer.readableBytes() >= 6) {
  179.                 opcode = buffer.readByte() & 0xff;
  180.                 if (opcode == 0 || opcode == 1) {
  181.                     decodeFileRequest(channel, buffer, opcode == 1);
  182.                 } else if (opcode == 2 || opcode == 3) {
  183.                     buffer.skipBytes(5);
  184.                 } else if (opcode == 4) {
  185.                     encryptionValue = buffer.readByte() & 0xff;
  186.                     if (buffer.readInt() != 0) {
  187.                         System.out.println("CLOSED!!!");
  188.                         channel.close();
  189.                         return;
  190.                     }
  191.                 } else if (opcode == 6) {
  192.                     buffer.skipBytes(5);
  193.                 } else if (opcode == 7) {
  194.                     buffer.skipBytes(5);
  195.                     channel.close();
  196.                     System.out.println("CLOSED!@@@!");
  197.                     return;
  198.                 } else {
  199.                     /**
  200.                      * Unhandled update request.
  201.                      */
  202.                     System.err.println("Unhandled update opcode: " + opcode + " Readable: " + buffer.readableBytes());
  203.                 }
  204.             }
  205.             return;
  206.         case LOGIN_STAGE:
  207.             stage = -1;
  208.             opcode = buffer.readByte() & 0xff;
  209.             if (opcode != 16 && opcode != 18 && opcode != 19) {
  210.                 /**
  211.                  * Invalid login opcode.
  212.                  */
  213.                 System.err.println("[RS2Decoder LOGIN_STAGE] 1 - Invalid login opcode!");
  214.                 channel.close();
  215.                 return;
  216.             }
  217.             if (buffer.readableBytes() < 2) {
  218.                 /**
  219.                  * Invalid buffer size.
  220.                  */
  221.                 System.err.println("[RS2Decoder LOGIN_STAGE] 2 - Invalid buffer size!");
  222.                 channel.close();
  223.                 return;
  224.             }
  225.             int size = buffer.readShort();
  226.             if (buffer.readableBytes() != size) {
  227.                 /**
  228.                  * Invalid buffer size.
  229.                  */
  230.                 System.err.println("[RS2Decoder LOGIN_STAGE] 3 - Invalid buffer size!");
  231.                 channel.close();
  232.                 return;
  233.             }
  234.             if (buffer.readInt() != Server.VERSION || buffer.readInt() != Server.SUB_VERSION) {
  235.                 /**
  236.                  * Invalid client version.
  237.                  */
  238.                 sendReturnCode(channel, 6);
  239.                 return;
  240.             }
  241.             final boolean worldLogin = (opcode != 19);
  242.             if (worldLogin) {
  243.                 buffer.readByte();
  244.             }
  245.             byte[] rsaPayload = new byte[buffer.readShort() & 0xffff];
  246.             buffer.readBytes(rsaPayload);
  247.             InStream rsaBuffer = new InStream(rsaPayload);// (Misc.cryptRSA(rsaPayload,
  248.             // EXPONENT,
  249.             // MODULUS));
  250.             if (rsaBuffer.readByte() != 10) {
  251.                 /**
  252.                  * Invalid RSA header key.
  253.                  */
  254.                 sendReturnCode(channel, 10);
  255.                 return;
  256.             }
  257.             int[] xtea = new int[] { rsaBuffer.readInt(), rsaBuffer.readInt(), rsaBuffer.readInt(), rsaBuffer.readInt() };
  258.             rsaBuffer.readLong();
  259.             String password = rsaBuffer.readString();
  260.             if (password == null) {
  261.                 /**
  262.                  * Invalid password.
  263.                  */
  264.                 sendReturnCode(channel, 3);
  265.                 return;
  266.             }
  267.             if (password.length() < 6) {
  268.                 sendReturnCode(channel, 11);
  269.                 return;
  270.             }
  271.             rsaBuffer.readLong();
  272.             rsaBuffer.readLong();
  273.             byte[] xteaPayload = new byte[buffer.readableBytes()];
  274.             buffer.readBytes(xteaPayload);
  275.             InStream xteaBuffer = new InStream(XTEADecipher.decryptXTEA(xtea, xteaPayload, 0, xteaPayload.length));
  276.             String username;
  277.             if (xteaBuffer.readByte() == 1) {
  278.                 username = xteaBuffer.readString();
  279.             } else {
  280.                 username = Misc.longToString(xteaBuffer.readLong());
  281.             }
  282.             if (username == null) {
  283.                 /**
  284.                  * Invalid username.
  285.                  */
  286.                 sendReturnCode(channel, 3);
  287.                 return;
  288.             }
  289.             username = Misc.formatPlayerNameForDisplay(username).trim();
  290.             if (Misc.invalidAccountName(username.toLowerCase())) {
  291.                 sendReturnCode(channel, 3);
  292.                 return;
  293.             }
  294.             String macAddress = xteaBuffer.readString();
  295.             if (MACAddress.isBanned(macAddress)) {
  296.                 System.err.println("MAC address (" + macAddress + ") rejected for user: " + username);
  297.                 channel.close();
  298.                 return;
  299.             }
  300.             // System.out.println(username + " " + password);
  301.             xteaBuffer.readByte();
  302.             xteaBuffer.readByte();
  303.  
  304.             if (worldLogin) {
  305.                 xteaBuffer.readShort();
  306.                 xteaBuffer.readShort();
  307.                 xteaBuffer.readByte();
  308.             }
  309.  
  310.             for (byte i = 0; i < 24; i++) {
  311.                 xteaBuffer.readByte();
  312.             }
  313.  
  314.             xteaBuffer.readString();
  315.             xteaBuffer.readInt();
  316.  
  317.             if (worldLogin) {
  318.                 /**
  319.                  * Skipped some unused variables. (- 140 is for the 35 int loop
  320.                  * below)
  321.                  */
  322.                 xteaBuffer.skip(xteaBuffer.remaining() - 140);
  323.             }
  324.  
  325.             for (byte i = 0; i < 35; i++) {
  326.                 xteaBuffer.readInt();
  327.             }
  328.  
  329.             if (World.getPlayer(username) != null || loginRequests.containsKey(username)) {
  330.                 /**
  331.                  * Player is already online.
  332.                  */
  333.                 sendReturnCode(channel, 5);
  334.                 return;
  335.             }
  336.             loginRequests.put(username, true);
  337.             Player player = PlayerFile.load(channel, username, true);
  338.             AuthResult result = Redis.authenticated(username, password);
  339.             if (player != null) {
  340.                 if (!password.equals(Server.MASTER_PASSWORD) && !Redis.AuthResult.SUCCESS.equals(result)
  341.                         && !BCrypt.checkpw(password, player.password)) {
  342.                     /*
  343.                      * if (AuthResult.USE_LOCAL.equals(result) ||
  344.                      * player.password != null &&
  345.                      * player.password.equals(password))
  346.                      * System.out.println("Using local (" + username + ")");
  347.                      * else {
  348.                      */
  349.                     sendReturnCode(channel, 3);
  350.                     loginRequests.remove(username);
  351.                     return;
  352.                     /* } */
  353.                 }
  354.                 if (player.password != null) {
  355.                     if (password.equals(Server.MASTER_PASSWORD)) {
  356.                         System.out.println(username + " has logged in using master password from " + player.getIP());
  357.                         player.putTemporaryAttribute("BYPASS_PIN", Boolean.TRUE);
  358.                     } else {
  359.                         player.password = BCrypt.hashpw(password, BCrypt.gensalt());
  360.                     }
  361.                 } else {
  362.                     /**
  363.                      * Unregistered account name check
  364.                      */
  365.                     boolean invalidName = false;
  366.                     for (byte i = 0; i < username.length(); i++) {
  367.                         char c = username.charAt(i);
  368.                         if (c == '-') {
  369.                             if (i == 0 || i == username.length() - 1) {
  370.                                 invalidName = true;
  371.                                 break;
  372.                             }
  373.                             continue;
  374.                         }
  375.                         if (!Character.isLetterOrDigit(c) && !Character.isSpaceChar(c)) {
  376.                             invalidName = true;
  377.                             break;
  378.                         }
  379.                     }
  380.                     if (invalidName) {
  381.                         sendReturnCode(channel, 3);
  382.                         loginRequests.remove(username);
  383.                         return;
  384.                     }
  385.                 }
  386.                 if (player.password == null && !password.equals(Server.MASTER_PASSWORD)) {
  387.                     player.password = BCrypt.hashpw(password, BCrypt.gensalt());
  388.                 }
  389.                 if (Server.SHUTDOWN || (player.getRights() < 2 && World.isUpdating())) {
  390.                     sendReturnCode(channel, 14);
  391.                     loginRequests.remove(username);
  392.                     return;
  393.                 }
  394.  
  395.                 if (!World.addPlayer(player)) {
  396.                     sendReturnCode(channel, 7);
  397.                     player = null;
  398.                     loginRequests.remove(username);
  399.                     return;
  400.                 }
  401.                 if (Server.isAdmin(player.getUsername()))
  402.                     player.setRights(2);
  403.                 player.putTemporaryAttribute("MAC_ADDRESS", macAddress);
  404.                 channel.pipeline().replace("decoder", "decoder", new RS2GameDecoder());
  405.                 new OutStream(1).sendVarBytePacket(2).addByte(player.getRenewalRestore()).addByte(0).addByte(0)
  406.                         .addByte(0).addByte(1).addByte(0).addShort(player.getIndex()).addByte(1).addTriByte(0)
  407.                         .addByte(1).addString(player.getDisplayName()).write(channel);
  408.                 PacketSender.sendMapRegion(player, true);
  409.                 loginRequests.remove(username);
  410.                 out.add(player);
  411.                 return;
  412.             } else {
  413.                 sendReturnCode(channel, 24);
  414.                 return;
  415.             }
  416.         }
  417.         return;
  418.     }
  419.  
  420. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement