Esempio n. 1
0
        public IStorageUser AddUser(string name, string token, GeoIp geo_ip, string id = null)
        {
            IStorageUser user = new IStorageUser()
            {
                Id       = string.IsNullOrEmpty(id) ? Guid.NewGuid() : id.UrnToGuid(),
                Token    = token,
                UserName = name,
                Devices  = new List <Guid>()
            };
            TableOperation insertOperation = TableOperation.Insert(AzureStorage.CreateUserTableEntity(user));
            TableResult    result;

            try
            {
                result = this.UsersTable.Execute(insertOperation);
                Log.WriteTableSuccess(string.Format("Added user entity: {0}, Id: {1}, Token {2}.",
                                                    user.UserName, user.Id.ToUrn(), user.Token));
                return(user);
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format("Failed to add user entity: {0}, Id: {1}, Token {2}.",
                                                    user.UserName, user.Id.ToUrn(), user.Token), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddUser);
            }
        }
Esempio n. 2
0
        public IStorageDevice AddDevice(string name, string token, GeoIp location,
                                        string id = null)
        {
            IStorageUser user = this.GetCurrentUser();

            return(this.AddDevice(user, name, token, location));
        }
        public async Task should_get_geo_by_ip()
        {
            var geo    = new GeoIp(_client);
            var actual = await geo.DoLookUp("1.1.1.1", AddressType.Ip);

            Assert.IsNotNull(actual.Data);
            Assert.AreEqual(ServiceStatus.Ok, actual.Status);
        }
        public async Task should_get_geo_by_domain()
        {
            var geo    = new GeoIp(_client);
            var actual = await geo.DoLookUp("calebukle.com", AddressType.DomainName);

            Assert.IsNotNull(actual.Data);
            Assert.AreEqual(ServiceStatus.Ok, actual.Status);
        }
Esempio n. 5
0
        private string IpGeoList = "www.acgdraw.com@0|lab.acgdraw.com@0"; // Padding Data

        // Parse IP to GEO via IP2API public service
        public string Parse(string Host)
        {
            string GeoRet = string.Empty;

            // If Host not a Ip skip it
            if (IPAddress.TryParse(Host, out _))
            {
                // If host already in the list, parse via list
                foreach (string GeoIp in IpGeoList.Split('|'))
                {
                    string Ip  = GeoIp.Split('@')[0];
                    string Geo = GeoIp.Split('@')[1];

                    if (Ip == Host)
                    {
                        return(Geo);
                    }
                }

                // If not in list try parse via IPIPNET
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        wc.Encoding = System.Text.Encoding.UTF8;
                        wc.Headers.Add("User-Agent", "BestTrace/Windows V3.7.3");
                        var    json  = wc.DownloadString($"{IpQueryServer}{Host}");
                        JToken token = JObject.Parse(json);
                        // replace string
                        GeoRet = (string)token.SelectToken("area");
                        GeoRet = GeoRet.Replace("\t\t", "_ntr_")
                                 .Replace("\t-", "")
                                 .Replace("\t", "")
                                 .Replace("_ntr_", "  ");
                        GeoRet = Regex.Replace(GeoRet, @"\d*\.\d*", "");
                        // replace LAN string
                        GeoRet = GeoRet.Contains("局域网") ? "本地局域网" : GeoRet;
                        GeoRet = GeoRet.Contains("LAN Address") ? "Local Area Network" : GeoRet;

                        // Store to local List
                        IpGeoList += $"|{Host}@{GeoRet}";
                        wc.Dispose();
                    }
                }
                catch
                { }
            }

            return(GeoRet);
        }
Esempio n. 6
0
        public async Task <GeoIp> GetGeoIpInformation(string domain)
        {
            var serializer = new DataContractJsonSerializer(typeof(GeoIp));

            string url   = FreeIpUri + domain;
            GeoIp  geoIp = null;
            HttpResponseMessage response = await _client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var streamTask = response.Content.ReadAsStreamAsync();
                geoIp = serializer.ReadObject(await streamTask) as GeoIp;
            }

            return(geoIp);
        }
Esempio n. 7
0
        public IGeoIp Resolve(string address)
        {
            var geoIp = new GeoIp();

            if (this.hasCity)
            {
                bool found = this.reader.TryCity(address, out var city);
                if (!found)
                {
                    return(null);
                }

                geoIp.Location      = new GeoLocation(city.Location.Latitude, city.Location.Longitude);
                geoIp.ContinentCode = city.Continent?.Code;
                geoIp.CountryCode   = city.Country?.IsoCode;
                geoIp.RegionCode    = city.MostSpecificSubdivision?.IsoCode;
                geoIp.PostalCode    = city.Postal?.Code;

                geoIp.ContinentNames = city.Continent?.Names;
                geoIp.CountryNames   = city.Country?.Names;
                geoIp.RegionNames    = city.MostSpecificSubdivision?.Names;
                geoIp.CityNames      = city.City?.Names;

                return(geoIp);
            }
            else
            {
                bool found = this.reader.TryCountry(address, out var country);
                if (!found)
                {
                    return(null);
                }

                geoIp.ContinentCode = country.Continent?.Code;
                geoIp.CountryCode   = country.Country?.IsoCode;

                geoIp.ContinentNames = country.Continent?.Names;
                geoIp.CountryNames   = country.Country?.Names;

                return(geoIp);
            }
        }
Esempio n. 8
0
        public async Task <bool> SetNodeDetails(bitcoin_lib.P2P.Version v)
        {
            var ipb = IP.ToByteArray();

            await SetAsGoodNode();

            if (await db.HashSetAsync($"hs:nodes:detail:{IP.ToString()}", "version", v.ToArray()))
            {
                await db.HashSetAsync($"hs:nodes:detail:{IP.ToString()}", "first_seen", DateTime.Now.Ticks);

                var gloc = GeoIp.City(IP.Address);
                if (gloc.Location.HasCoordinates)
                {
                    await db.GeoAddAsync("hs:nodes:geo", new GeoEntry(gloc.Location.Longitude.Value, gloc.Location.Latitude.Value, ipb));
                }

                return(true);
            }
            return(false);
        }
Esempio n. 9
0
        private string IpGeoList = "www.acgdraw.com@0|lab.acgdraw.com@0"; // Padding Data

        // Parse IP to GEO via IP2API public service
        public string Parse(string Host)
        {
            string GeoRet = string.Empty;

            // If Host not a Ip skip it
            if (IPAddress.TryParse(Host, out _))
            {
                // If host already in the list, parse via list
                foreach (string GeoIp in IpGeoList.Split('|'))
                {
                    string Ip  = GeoIp.Split('@')[0];
                    string Geo = GeoIp.Split('@')[1];

                    if (Ip == Host)
                    {
                        return(Geo);
                    }
                }

                // If not in list try parse via IP2API
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        var    json  = wc.DownloadString($"{IpQueryServer}{Host}");
                        JToken token = JObject.Parse(json);
                        GeoRet = (string)token.SelectToken("country") + " " + (string)token.SelectToken("city");

                        // Store to local List
                        IpGeoList += $"|{Host}@{GeoRet}";
                        wc.Dispose();
                    }
                }
                catch
                { }
            }

            return(GeoRet);
        }
Esempio n. 10
0
        /// <summary>
        /// Inicializa o servidor
        /// </summary>
        public void InitializeServer()
        {
            trayIcon = new NotifyIcon();
            trayMenu = new ContextMenu();

            LuaScript.LuaConfig.InitializeConfig();

            Configuration.ParseConfigFile($"{Environment.CurrentDirectory}\\{Settings.FILE_CONFIG}");

            Settings.Discovery = Configuration.GetString("Discovery");
            WriteLog($"Discovery: {Settings.Discovery}", Color.Black);

            Settings.Port = Configuration.GetInt32("Port");
            WriteLog($"Port: {Settings.Port}", Color.Black);

            Settings.MaxConnection = Configuration.GetInt32("MaximumConnections");
            WriteLog($"MaxConnection: {Settings.MaxConnection}", Color.Black);

            Settings.ConnectionTimeOut = Configuration.GetInt32("ConnectionTimeOut");
            WriteLog($"ConnectionTimeOut: {Settings.ConnectionTimeOut}", Color.Black);

            Settings.LogSystem = Configuration.GetByte("LogSystem");
            WriteLog($"LogSystem: {Settings.LogSystem}", Color.Black);

            Settings.Sleep = Configuration.GetInt32("Sleep");
            WriteLog($"Sleep: {Settings.Sleep}", Color.Black);

            Settings.Version = Configuration.GetString("CheckVersion");
            WriteLog($"Version: {Settings.Version}", Color.BlueViolet);

            GeoIp.Enabled = Configuration.GetBoolean("GeoIp");
            var result = (GeoIp.Enabled == true) ? "Ativado" : "Desativado";

            WriteLog($"GeoIp: {result}", Color.BlueViolet);

            CheckSum.Enabled = Configuration.GetBoolean("CheckSum");
            result           = (CheckSum.Enabled == true) ? "Ativado" : "Desativado";
            WriteLog($"CheckSum: {result}", Color.BlueViolet);

            //1 - enabled
            result = (Settings.LogSystem == 1) ? "LogSystem: Ativado" : "LogSystem: Desativado";
            WriteLog("LogSystem: Desativado.", Color.Black);

            if (Settings.LogSystem == 1)
            {
                FileLog.OpenFileLog();
            }

            Authentication.Player = new HashSet <PlayerData>();

            InitializeServerConfig();
            InitializeDatabaseConfig();

            var tempError = string.Empty;

            if (!Common_DB.Open(out tempError))
            {
                WriteLog(tempError, Color.Red);
            }
            else
            {
                WriteLog("Connectado ao banco de dados", Color.Green);
            }

            WriteLog("Conectando World Server.", Color.Green);

            WorldNetwork.InitializeWorldServer();

            WriteLog("Login Server Start.", Color.Green);

            LoginNetwork.InitializeServer();

            GeoIp.ReadFile();

            #region Tray System
            trayMenu.MenuItems.Add("Mostrar", ShowForm);
            trayMenu.MenuItems.Add("Sair", quit_MenuItem_Click);

            trayIcon.Text = "Connect Server @";
            trayIcon.Icon = this.Icon;

            trayIcon.ContextMenu = trayMenu;
            #endregion
        }
Esempio n. 11
0
        public IStorageDevice AddDevice(IStorageUser user, string name, string token, GeoIp location,
                                        string id = null)
        {
            IStorageDevice device = new IStorageDevice()
            {
                Id      = string.IsNullOrEmpty(id) ? Guid.NewGuid() : id.UrnToGuid(),
                UserId  = user.Id,
                Token   = token,
                Name    = name,
                Sensors = new Dictionary <string, IStorageSensor>()
            };

            try
            {
                TableOperation insert_device_operation = TableOperation
                                                         .Insert(AzureStorage.CreateDeviceTableEntity(device));
                TableResult result;
                result      = this.DevicesTable.Execute(insert_device_operation);
                device.ETag = result.Etag;
                user.Devices.Add(device.Id);
                TableOperation update_user_operation = TableOperation.Merge(CreateUserTableEntity(user));
                result    = this.UsersTable.Execute(update_user_operation);
                user.ETag = result.Etag;
                Log.WriteTableSuccess(string.
                                      Format("Added device entity: {0}, Id: {1}, Token {2} to Devices table.",
                                             device.Name, device.Id.ToUrn(), device.Token));
                Log.WriteTableSuccess(string.Format("Added device entity: {0}, Id: {1}, to User entity {2}.",
                                                    device.Name, device.Id.ToUrn(), device.Token, user.Id.ToUrn()));
                return(device);
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format("Failed to add device entity: {0}, Id: {1}, Token {2}.",
                                                    device.Name, device.Id.ToUrn(), device.Token), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddDevice);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Recebe os dados dos clientes.
        /// </summary>
        public static void ReceivedData()
        {
            while ((msg = socket.ReadMessage()) != null)
            {
                pData = Authentication.FindByConnection(msg.SenderConnection);

                switch (msg.MessageType)
                {
                case NetIncomingMessageType.DiscoveryRequest:

                    #region Find Banned Country
                    var ip = msg.SenderEndPoint.Address.ToString();

                    if (GeoIp.Enabled)
                    {
                        //Verifica se o ip já está bloqueado temporariamente (evitar processamento desnecessario)
                        if (!GeoIp.IsIpBlocked(ip))
                        {
                            //verifica se o ip do país está na lista de bloqueados.
                            if (GeoIp.IsCountryIpBlocked(ip))
                            {
                                var country = GeoIp.FindCountryByIp(ip);

                                //adiciona na lista de bloqueado temporareamente
                                GeoIp.AddIpAddress(ip);
                                FileLog.WriteLog($"Banned country trying to connect: {ip} {country.Country}-{country.Code}", Color.Coral);
                                return;
                            }
                        }
                        else
                        {
                            return;
                        }
                    }

                    #endregion

                    #region Find Banned IP
                    if (Accounts_DB.IsBannedIp(msg.SenderEndPoint.Address.ToString()) == true)
                    {
                        FileLog.WriteLog("Warning: Attempted IP Banned " + msg.SenderEndPoint.Address, Color.Coral);
                        return;
                    }
                    #endregion

                    LoginNetwork.socket.SendDiscoveryResponse(null, msg.SenderEndPoint);
                    FileLog.WriteLog($"Discovery Response IPEndPoint: {msg.SenderEndPoint.Address}", Color.Coral);
                    break;

                case NetIncomingMessageType.ErrorMessage:
                    FileLog.WriteLog($"Error: {msg.ReadString()}", Color.Coral);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    #region Status Changed Connected
                    NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                    if (status == NetConnectionStatus.Connected)
                    {
                        FileLog.WriteLog($"Status changed to connected: {msg.SenderEndPoint.Address}", Color.Coral);
                        Authentication.Player.Add(new PlayerData(msg.SenderConnection, NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier), msg.SenderEndPoint.Address.ToString()));
                    }
                    #endregion

                    #region Status Changed Disconnected
                    if (status == NetConnectionStatus.Disconnected)
                    {
                        if (pData == null)
                        {
                            return;
                        }

                        FileLog.WriteLog($"Status changed to disconnected: {pData?.ID} {pData?.Account} {msg?.SenderEndPoint.Address} {pData?.HexID}", Color.Coral);

                        Accounts_DB.UpdateLastIP(pData.Account, pData.IP);
                        Accounts_DB.UpdateLoggedIn(pData.Account, 0);             //0 disconnect
                        Accounts_DB.UpdateCurrentIP(pData.Account, string.Empty); //limpa o ip atual

                        Authentication.Player.Remove(pData);
                    }
                    #endregion
                    break;

                case NetIncomingMessageType.Data:
                    LoginData.HandleData(pData.HexID, msg);
                    break;

                default:
                    //Registra qualquer mensagem invalida
                    FileLog.WriteLog($"Unhandled type: {msg.MessageType}", Color.DarkRed);
                    break;
                }

                LoginNetwork.socket.Recycle(msg);
            }
        }
Esempio n. 13
0
        public async Task UpdateNodeInfo(Node n)
        {
            //Console.WriteLine($"Update node info: {n.IP}");
            try
            {
                //try to connect to the node to get version info and to get its peers
                var ns = new Socket(SocketType.Stream, ProtocolType.Tcp);
                await ns.ConnectAsync(n.IP);

                var p = new BitcoinPeer(ns);
                //Console.WriteLine($"Connected to {n.IP}");
                var ss = new SemaphoreSlim(0, 1);
                var db = Redis.GetDatabase();

                p.OnVersion += async(s, v) =>
                {
                    //send verack and log
                    var ip  = new IPEndPoint(((IPEndPoint)s.RemoteEndpoint).Address.MapToIPv6(), ((IPEndPoint)s.RemoteEndpoint).Port);
                    var ipb = ip.ToByteArray();
                    await db.HashSetAsync($"hs:nodes:detail:{ip.ToString()}", "version", v.ToArray());

                    if (await db.SortedSetAddAsync("hs:nodes:all-nodes", ipb, DateTime.Now.Ticks))
                    {
                        //Console.WriteLine($"Got new node: {ip}");
                        await db.SetRemoveAsync("hs:nodes:new-nodes", ipb);

                        var gloc = GeoIp.City(ip.Address);
                        if (gloc.Location.HasCoordinates)
                        {
                            await db.GeoAddAsync("hs:nodes:geo", new GeoEntry(gloc.Location.Longitude.Value, gloc.Location.Latitude.Value, ipb));
                        }
                    }


                    var va = new VerAck();
                    await s.WriteMessage(va);

                    var ga = new GetAddr();
                    await s.WriteMessage(ga);
                };

                p.OnAddr += async(s, a) =>
                {
                    //Console.WriteLine($"Got {a.IpCount.Value} ips");
                    foreach (var ip in a.Ips)
                    {
                        var ep  = new IPEndPoint(ip.Ip.MapToIPv6(), ip.Port);
                        var epb = ep.ToByteArray();
                        if (await db.SetAddAsync("hs:nodes:new-nodes", epb))
                        {
                            //Console.WriteLine($"Got new node: {ep}");
                        }
                    }

                    s.Stop();

                    ss.Release();

                    //Console.WriteLine($"Disconnected from {n.IP}");
                };

                p.Start();

                Ver.Timestamp = (UInt64)DateTimeOffset.Now.ToUnixTimeSeconds();

                await p.WriteMessage(Ver);

                await ss.WaitAsync(TimeSpan.FromSeconds(5));
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
            }
        }
Esempio n. 14
0
 public EventInformation(EventData eventData, GeoIp geoIp)
 {
     Event   = eventData;
     GeoInfo = geoIp;
 }