@Override public void run() { HttpURLConnection connection = null; String response = ""; try { URL url = new URL(URL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty( "Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream e = new DataOutputStream(connection.getOutputStream()); e.writeBytes(urlParameters); e.flush(); e.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append('\r'); } rd.close(); response = responseBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } if (VanillaPlugin.getInstance().getEngine().debugMode()) { Spout.getLogger().info("Authentification: " + response); } if (response.contains(":")) { String[] infos = response.split(":"); VanillaPlugin.getInstance().setClientAuthInfos(infos[2], infos[3]); } else { Spout.getLogger().info("Authentification failed: " + response); } }
private SecureRandom getSecureRandom(String RNGAlgorithm, String RNGProvider) { try { SecureRandom r; if (RNGProvider != null) { r = SecureRandom.getInstance(RNGAlgorithm, RNGProvider); } else { r = SecureRandom.getInstance(RNGAlgorithm); } r.nextBytes(new byte[1]); return r; } catch (NoSuchProviderException e) { // Fallback to any provider for the algorithm return getSecureRandom(RNGAlgorithm, null); } catch (NoSuchAlgorithmException e) { if (RNGProvider != null) { return getSecureRandom(RNGAlgorithm, null); } Spout.getLogger() .severe( "Unable to find algorithm to generate random number generator for key pair creation (" + RNGAlgorithm + ", " + RNGProvider + ")"); return null; } }
public byte[] processAll(AsymmetricBlockCipher cipher, byte[] input) { int outputSize = 0; int blockSize = cipher.getInputBlockSize(); List<byte[]> outputBlocks = new LinkedList<>(); int pos = 0; while (pos < input.length) { int length = Math.min(input.length - pos, blockSize); byte[] result; try { result = cipher.processBlock(input, pos, length); } catch (InvalidCipherTextException e) { Spout.getLogger().info("Error processing encrypted data"); return null; } outputSize += result.length; outputBlocks.add(result); pos += length; } byte[] output = new byte[outputSize]; pos = 0; for (byte[] block : outputBlocks) { System.arraycopy(block, 0, output, pos, block.length); pos += block.length; } return output; }
@Override public void save(Writer writer) { Yaml yaml = new Yaml(); LinkedHashMap<String, Object> dump = new LinkedHashMap<>(); dump.put("nextId", nextId); LinkedHashMap<Integer, LinkedHashMap<String, String>> ids = new LinkedHashMap<>(); for (Entry<String, HashMap<String, Integer>> e1 : classes.entrySet()) { for (Entry<String, Integer> e2 : e1.getValue().entrySet()) { String clazz = e1.getKey(); String source = e2.getKey(); int key = e2.getValue(); LinkedHashMap<String, String> v = new LinkedHashMap<>(2); v.put("class", clazz); v.put("string", source); ids.put(key, v); } } dump.put("ids", ids); String toWrite = yaml.dumpAs(dump, Tag.MAP, FlowStyle.BLOCK); try { writer.write(toWrite); } catch (IOException e) { Spout.getLogger().log(Level.SEVERE, "unable to save dictionary", e); } finally { IOUtils.closeQuietly(writer); } }
@Override public byte[] compress() { Serializable value = data.get(); if (value instanceof ByteArrayWrapper) { return ((ByteArrayWrapper) value).getArray(); } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try { ObjectOutputStream objOut = new ObjectOutputStream(byteOut); objOut.writeObject(value); objOut.flush(); objOut.close(); } catch (IOException e) { if (Spout.debugMode()) { Spout.getLogger() .log( Level.SEVERE, "Unable to serialize " + value + " (type: " + (value != null ? value.getClass().getSimpleName() : "null") + ")", e); } return null; } return byteOut.toByteArray(); }
public AsymmetricCipherKeyPairGenerator getGenerator(String algorithm) { if (algorithm.equals("RSA")) { return new RSAKeyPairGenerator(); } Spout.getLogger().info("Unable to find key generator " + algorithm); return null; }
static { Provider p = Security.getProvider("BC"); if (p == null) { Security.addProvider(new BouncyCastleProvider()); p = Security.getProvider("BC"); if (p == null) { Spout.getLogger().info("Unable to start security provider"); } } provider = p; instance = new SecurityHandler(); }
@SuppressWarnings("unchecked") protected void loadLanguage(InputStream in, String fileName) { Yaml yaml = new Yaml(); Map<String, Object> dump = (Map<String, Object>) yaml.load(in); Locale locale = null; if (dump.containsKey("locale")) { locale = Locale.getByCode((String) dump.get("locale")); } if (locale == null) { throw new IllegalStateException("No locale was set in the file " + fileName); } LanguageDictionary dict = new LanguageDictionary(locale); setDictionary(locale, dict); if (dump.containsKey("strings")) { Map<Integer, Object> strings = (Map<Integer, Object>) dump.get("strings"); for (Entry<Integer, Object> e : strings.entrySet()) { if (e.getValue() instanceof String) { dict.setTranslation(e.getKey(), e.getValue()); } else { try { LocaleNumberHandler handler = locale.getNumberHandler().newInstance(); handler.init(e.getValue()); dict.setTranslation(e.getKey(), handler); } catch (IllegalArgumentException e1) { throw new RuntimeException( "Could not construct a LocaleNumberHandler, check if you used correct syntax (in file " + fileName + ")"); } catch (SecurityException e1) { Spout.getLogger().log(Level.SEVERE, "Failed to construct LocaleNumberHandler", e1); } catch (InstantiationException e1) { Spout.getLogger().log(Level.SEVERE, "Failed to construct LocaleNumberHandler", e1); } catch (IllegalAccessException e1) { Spout.getLogger().log(Level.SEVERE, "Failed to construct LocaleNumberHandler", e1); } } } } }
private BufferedBlockCipher addSymmetricWrapper(BlockCipher rawCipher, String wrapper) { if (wrapper.startsWith("CFB")) { int bits; try { bits = Integer.parseInt(wrapper.substring(3)); } catch (NumberFormatException e) { Spout.getLogger().info("Unable to parse bits for CFB wrapper from: " + wrapper); return null; } return new BufferedBlockCipher(new CFBBlockCipher(rawCipher, bits)); } return new BufferedBlockCipher(rawCipher); }
@Override public void run() { boolean dead = false; while (!dead && !interrupted()) { try { Thread.sleep(10000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); dead = true; } ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { Spout.getLogger().info("Checking for deadlocks"); ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true); Spout.getLogger().severe("The following threads are deadlocked:"); for (ThreadInfo ti : infos) { Spout.getLogger().severe(ti.toString()); } } } }
@Override public void onTick(float dt) { final Random random = GenericMath.getRandom(); float secondsUntilWeatherChange = sky.getData().get(VanillaData.WEATHER_CHANGE_TIME); secondsUntilWeatherChange -= dt; if (forceWeatherUpdate.compareAndSet(true, false) || secondsUntilWeatherChange <= 0) { this.sky.updateWeather(getCurrent(), getForecast()); sky.getData().put(VanillaData.WORLD_WEATHER, getForecast()); final Weather current = getCurrent(); Weather forecast = current; while (forecast == current) { // When Rain/Snow or Thunderstorms occur, always go to Clear after. if (current == Weather.RAIN || current == Weather.THUNDERSTORM) { forecast = Weather.CLEAR; } else { forecast = Weather.get(random.nextInt(3)); } setForecast(forecast); } setForecast(forecast); secondsUntilWeatherChange = current.getBaseWeatherTime() + random.nextInt(current.getRandomWeatherTime()); if (Spout.debugMode()) { Spout.getLogger() .info( "Weather changed to: " + current + ", next change in " + secondsUntilWeatherChange / 1000F + "s"); } } float currentRainStrength = sky.getData().get(VanillaData.CURRENT_RAIN_STRENGTH); sky.getData().put(VanillaData.PREVIOUS_RAIN_STRENGTH, currentRainStrength); if (this.isRaining()) { currentRainStrength = Math.min(1.0f, currentRainStrength + 0.01f); } else { currentRainStrength = Math.max(0.0f, currentRainStrength - 0.01f); } sky.getData().put(VanillaData.CURRENT_RAIN_STRENGTH, currentRainStrength); if (hasLightning()) { lightning.onTick(dt); } if (getCurrent().isRaining()) { snowfall.onTick(dt); } sky.getData().put(VanillaData.WEATHER_CHANGE_TIME, secondsUntilWeatherChange); }
public static ChunkInit getChunkInit(String init) { if (init == null) { return CLIENT_SEL; } else if (isEqual(init, "auto", "client", "client_sel")) { return CLIENT_SEL; } else if (isEqual(init, "full", "fullcol", "full_column")) { return FULL_COLUMN; } else if (isEqual(init, "empty", "emptycol", "empty_column")) { return EMPTY_COLUMN; } else if (isEqual(init, "heightmap", "height_map")) { return HEIGHTMAP; } else { Spout.getLogger() .info("Invalid chunk init setting, " + init + ", using default setting auto"); Spout.getLogger().info("Valid settings are:"); Spout.getLogger().info("client_sel Allows client selection, defaults to full columns"); Spout.getLogger().info("fullcol Sends full columns"); Spout.getLogger().info("heightmap Sends a heightmap including the topmost block"); Spout.getLogger().info("empty Sends empty columns"); return CLIENT_SEL; } }
public void run() { long start = System.currentTimeMillis(); String sessionId = session.getDataMap().get(VanillaProtocol.SESSION_ID); String encodedUser; String encodedId; try { encodedUser = URLEncoder.encode(name, "UTF-8"); encodedId = URLEncoder.encode(sessionId, "UTF-8"); } catch (UnsupportedEncodingException e) { failed("Unable to uncode username or sessionid"); return; } String fullURL = URLBase + userPrefix + encodedUser + idPrefix + encodedId; URL authURL; try { authURL = new URL(fullURL); } catch (MalformedURLException e2) { failed("Unable to parse URL"); return; } URLConnection connection; try { connection = authURL.openConnection(); } catch (IOException e2) { failed("Unable to open connection"); return; } if (!(connection instanceof HttpURLConnection)) { failed("Unable to open http connection"); return; } HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setConnectTimeout(30000); httpConnection.setReadTimeout(30000); try { httpConnection.connect(); } catch (IOException e) { e.printStackTrace(); failed("Unable to connect to auth server"); return; } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String reply = in.readLine(); if (authString.equals(reply)) { if (runnable != null) { Spout.getEngine() .getScheduler() .scheduleSyncDelayedTask( VanillaPlugin.getInstance(), runnable, TaskPriority.CRITICAL); } } else { failed("Auth server refused authentication"); } } catch (IOException e) { e.printStackTrace(); failed("Unable to read reply from auth server"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } finally { httpConnection.disconnect(); } } else { httpConnection.disconnect(); } } if (Spout.getEngine().debugMode()) { Spout.getLogger().info("Authing took " + (System.currentTimeMillis() - start) + "ms"); } }
private void failed(String message) { Spout.getLogger().info("Kicking " + name + " due to problem authenticating {" + message + "}"); session.disconnect(message); }
protected void debug(Level level, String msg) { if (Spout.debugMode()) { Spout.getLogger().log(level, msg); } }