001/* 002 * Trident - A Multithreaded Server Alternative 003 * Copyright 2014 The TridentSDK Team 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package net.tridentsdk.server.packets.login; 019 020 021import com.google.common.collect.Maps; 022import net.tridentsdk.Trident; 023import net.tridentsdk.registry.Registered; 024 025import java.net.InetSocketAddress; 026import java.util.Map; 027import java.util.concurrent.ConcurrentHashMap; 028 029/** 030 * Class used to store login usernames during the login stage 031 */ 032public final class LoginHandler { 033 private static final long THROTTLE_MS = 4000L; 034 035 /** 036 * Instance of the class 037 */ 038 protected static final LoginHandler instance = new LoginHandler(); 039 040 /** 041 * Map used to store usernames with the address as the key 042 */ 043 protected final Map<InetSocketAddress, String> loginNames = Maps.newHashMap(); 044 private final Map<String, Long> times = new ConcurrentHashMap<>(); 045 046 protected LoginHandler() { 047 } 048 049 public static LoginHandler getInstance() { 050 return instance; 051 } 052 053 public boolean initLogin(InetSocketAddress address, String name) { 054 synchronized (this) { 055 return loginNames.size() + Registered.players().size() < Trident.info().maxPlayers() && 056 loginNames.put(address, name) == null && !throttled(name); 057 } 058 } 059 060 public String name(InetSocketAddress address) { 061 synchronized (this) { 062 return this.loginNames.get(address); 063 } 064 } 065 066 public void finish(InetSocketAddress address) { 067 synchronized (this) { 068 this.loginNames.remove(address); 069 } 070 } 071 072 private boolean throttled(String name) { 073 long time = System.currentTimeMillis(); 074 times.forEach((k, v) -> { 075 if (time - v > THROTTLE_MS) { 076 times.remove(k); 077 } 078 }); 079 080 boolean b = times.containsKey(name); 081 if (!b) { 082 times.put(name, System.currentTimeMillis()); 083 } 084 085 return b; 086 } 087}