示例#1
0
        /// <summary>
        /// Load data from the database
        /// </summary>
        public void LoadData()
        {
            Dto = new Dto2Object()
            {
                Zones = new List <PolyZone>()
            };

            int count = 0;

            if (MaxZones > 0)
            {
                count = MaxZones;
            }
            else
            {
                count = Sql.Instance.GetZoneCount();
            }

            var current = 0;

            Sql.Instance.LoadZones((zone) => {
                Dto.Zones.Add(zone);
                current++;

                ConsoleKit.Message(ConsoleKit.MessageType.INFO, "Loading {0}/{1} zones\t\r", current, count);
                return(true);
            }, count);
            Console.Write("\n");
        }
示例#2
0
        /// <summary>
        /// Produces a new MySqlConnection object that is used to
        /// execute queries and retrieve data from the MySQL database
        /// </summary>
        /// <param name="noDatabase">True if there is no database specified in the connection string</param>
        /// <returns></returns>
        private MySqlConnection GetConnection(bool noDatabase = false)
        {
            MySqlConnection mySqlConnection;

            if (noDatabase)
            {
                mySqlConnection = new MySqlConnection(
                    $@"SERVER={_server};PORT={_port};UID={_user};PASSWORD={_password};SslMode=none;Pooling=false");
            }
            else
            {
                mySqlConnection = new MySqlConnection(
                    $@"SERVER={_server};PORT={_port};DATABASE={_database};UID={_user};PASSWORD={_password};SslMode=none;Pooling=false");
            }


            try
            {
                mySqlConnection.Open();
            }
            catch (MySqlException e)
            {
                var error = e.GetExceptionNumber();
#if DEBUG
                Debug.WriteLine($"Database error {error}");
                Debugger.Break();
#else
                ConsoleKit.Message(ConsoleKit.MessageType.WARNING, "Database error {0}\n", error);
                Debugger.Break();
#endif
            }
            return(mySqlConnection);
        }
示例#3
0
        /// <summary>
        /// Invoked whenever a client disconnects from the server
        /// </summary>
        /// <param name="ipPort"></param>
        /// <returns></returns>
        private bool ClientDisconnected(string ipPort)
        {
            var user = Guard.GetAuthUser(ipPort);

            Guard.RemoveAuthUser(user);

            ConsoleKit.Message(ConsoleKit.MessageType.INFO, "Client disconnected: {0}\n", ipPort);
            BroadcastOnlineUsersAck();
            return(true);
        }
示例#4
0
 public void Handle()
 {
     _httpServer = new HttpServer {
         EndPoint = new IPEndPoint(IPAddress.Loopback, _httpPort)
     };
     _httpServer.RequestReceived += _httpServer_RequestReceived;
     _httpServer.Start();
     ConsoleKit.Message(ConsoleKit.MessageType.INFO, "HTTP server listening on {0}:{1}\n",
                        _httpServer.EndPoint.Address, _httpServer.EndPoint.Port);
 }
示例#5
0
        /// <summary>
        /// Start listening on the specified ip:port
        /// </summary>
        public void Listen()
        {
            ConsoleKit.Message(ConsoleKit.MessageType.INFO, "PP TCP Server starting up, protocol version {0}\n", Protocol.Version);

#if DEBUG
            _watsonTcpServer = new WatsonTcpServer(_ip, _port, ClientConnected, ClientDisconnected, MessageReceived, true);
#else
            _watsonTcpServer = new WatsonTcpServer(_ip, _port, ClientConnected, ClientDisconnected, MessageReceived, false);
#endif

            ConsoleKit.Message(ConsoleKit.MessageType.INFO, $"PP TCP server listening on {_ip}:{_port}\n");
        }
示例#6
0
        private async Task DataReceiver(ClientMetadata client)
        {
            try
            {
                #region Wait-for-Data

                while (true)
                {
                    try
                    {
                        if (!IsConnected(client))
                        {
                            break;
                        }

                        byte[] data = await MessageReadAsync(client);

                        if (data == null)
                        {
                            // no message available
                            await Task.Delay(30);

                            continue;
                        }

                        if (_MessageReceived != null)
                        {
                            Task <bool> unawaited = Task.Run(() => _MessageReceived(client.IpPort, data));
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleKit.Message(ConsoleKit.MessageType.ERROR, ex.Message + "\n" + ex.StackTrace + "\n");
                        break;
                    }
                }

                #endregion
            }
            finally
            {
                int activeCount = Interlocked.Decrement(ref _ActiveClients);
                RemoveClient(client);
                if (_ClientDisconnected != null)
                {
                    Task <bool> unawaited = Task.Run(() => _ClientDisconnected(client.IpPort));
                }
                Log("*** DataReceiver client " + client.IpPort + " disconnected (now " + activeCount + " clients active)");

                client.Dispose();
            }
        }
示例#7
0
        private void _httpServer_RequestReceived(object sender, HttpRequestEventArgs e)
        {
            e.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            try
            {
                e.Response.Headers.Add("Content-type", "application/json");

                var path    = System.Web.HttpUtility.UrlDecode(e.Request.Path);
                var request = Request.FromJson(path.Substring(path.IndexOf("=") + 1));

                var zones = new List <string>();

                var inBounds = false;
                foreach (var zone in Server.Dto.Zones)
                {
                    foreach (var point in zone.Geometry)
                    {
                        if (InBounds(point.Lat, point.Lng, request.North, request.East, request.South, request.West))
                        {
                            inBounds = true;
                            break;
                        }
                    }

                    if (inBounds)
                    {
                        zones.Add(JsonConvert.SerializeObject(zone, Converter.Settings));
                        inBounds = false;
                    }
                }

                using (var writer = new StreamWriter(e.Response.OutputStream))
                {
                    writer.Write($"{{ \"type\":\"ZoneCollection\", \"zones\": [{string.Join(",",zones.ToArray())}] }}");

                    ConsoleKit.Message(ConsoleKit.MessageType.DEBUG, "{0} zones served to {1}({2}) over HTTP\n",
                                       zones.Count, e.Request.UserHostAddress, e.Request.UserHostName);
                }
            }
            catch (Exception ex)
            {
                if (!(ex is MySqlException))
                {
                    ConsoleKit.Message(ConsoleKit.MessageType.WARNING, "Invalid HTTP request from {0}({1}), {2}\n",
                                       e.Request.UserHostAddress, e.Request.UserHostName, e.Request.Path);
                    e.Response.StatusCode = 500;
                    e.Response.Status     = "500 Internal Server Error";
                }
            }
        }
示例#8
0
 public void OnZoneListReq(string ipPort)
 {
     foreach (var zone in Server.Dto.Zones)
     {
         var zoneSerialized = JsonConvert.SerializeObject(zone, Converter.Settings);
         if (!_server.Send(ipPort, new ZoneListAck()
         {
             Zone = zoneSerialized
         }))
         {
             ConsoleKit.Message(ConsoleKit.MessageType.ERROR, "Connection lost ...\n", zone.Id);
             break;
         }
     }
 }
示例#9
0
        /// <summary>
        /// Processing and deserialization of incoming messages
        /// </summary>
        /// <param name="ipPort">IP:Port of the sender client</param>
        /// <param name="data">Byte array that contains data</param>
        /// <returns></returns>
        private bool MessageReceived(string ipPort, byte[] data)
        {
            if (data == null || data.Length <= 0)
            {
                return(false);
            }

            try
            {
                var ipOnly = ipPort.Split(':')[0];
                var user   = Guard.GetAuthUser(ipPort);

                // If the client is banned, drop the cconnection
                if (Guard.IsBanned(ipOnly) && !Guard.CheckExpired(ipOnly))
                {
                    throw new Exception($"Refused to process requests from {ipOnly}. Ip banned!");
                }

                using (var stream = new MemoryStream(data))
                {
                    // Check protocol version
                    // TODO: MessageReceived should not even get called if the protocol dont't match
                    var bProtocolVersion = new byte[4];
                    stream.Read(bProtocolVersion, 0, 4);
                    var protocolVersion = BitConverter.ToInt32(bProtocolVersion, 0);
                    if (protocolVersion != Protocol.Version)
                    {
                        throw new Exception($"Invalid protocol version {ipPort}");
                    }

                    // Fetch packet id
                    var bPacketId = new byte[4];
                    stream.Read(bPacketId, 0, 4);
                    var packetId = (Protocols)BitConverter.ToInt32(bPacketId, 0);

                    ConsoleKit.Message(ConsoleKit.MessageType.INFO, "PID {0} received from {1}\n", Enum.GetName(typeof(Protocols), packetId), ipPort);

                    // ReSharper disable once SwitchStatementMissingSomeCases
                    // Process each message type
                    switch (packetId)
                    {
                    case Protocols.LOGIN_REQ:
                        var  loginReq = Serializer.Deserialize <LoginReq>(stream);
                        User loginUser;

                        if (user != null)
                        {
                            Send(ipPort, new LoginDuplicateAck());
                        }
                        else
                        {
                            loginUser = _handler.OnLoginReq(loginReq, ipPort);

                            if (loginUser != null)
                            {
                                Guard.AddAuthUser(loginUser);
                                BroadcastOnlineUsersAck();
                            }
                            else
                            {
                                Guard.TryCheck(ipOnly);
                            }
                        }

                        break;

                    case Protocols.ZONECOUNT_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Guest))
                        {
                            goto default;
                        }

                        _handler.OnZoneCountReq(ipPort);
                        break;

                    case Protocols.ZONELIST_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Guest))
                        {
                            goto default;
                        }
                        _handler.OnZoneListReq(ipPort);
                        break;

                    case Protocols.INSERTZONE_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var insertZoneReq = Serializer.Deserialize <InsertZoneReq>(stream);
                        _handler.OnInsertZoneReqAsync(insertZoneReq, user);
                        break;

                    case Protocols.REMOVEZONE_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var removeZoneReq = Serializer.Deserialize <RemoveZoneReq>(stream);
                        _handler.OnRemoveZoneReq(removeZoneReq, user);
                        break;

                    case Protocols.UPDATEZONE_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var updateZoneReq = Serializer.Deserialize <UpdateZoneReq>(stream);
                        _handler.OnUpdateZoneReq(updateZoneReq, user);
                        break;

                    case Protocols.REMOVEPOINT_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var removePointReq = Serializer.Deserialize <RemovePointReq>(stream);
                        _handler.OnRemovePointReq(removePointReq, user);
                        break;

                    case Protocols.INSERTPOINT_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var insertPointReq = Serializer.Deserialize <InsertPointReq>(stream);
                        _handler.OnInsertPointReqAsync(insertPointReq, user);
                        break;

                    case Protocols.UPDATEPOINT_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        var updatePointReq = Serializer.Deserialize <UpdatePointReq>(stream);
                        _handler.OnUpdatePointReq(updatePointReq, user);
                        break;

                    case Protocols.CITYLIST_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Editor))
                        {
                            goto default;
                        }

                        _handler.OnCityListReqAsync(user);
                        break;

                    case Protocols.USERLIST_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        _handler.OnUserListReqAsync(user);
                        break;

                    case Protocols.INSERTUSER_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var insertUserReq = Serializer.Deserialize <InsertUserReq>(stream);
                        _handler.OnInsertUserReq(insertUserReq);
                        break;

                    case Protocols.REMOVEUSER_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var removeUserReq = Serializer.Deserialize <RemoveUserReq>(stream);
                        _handler.OnRemoveUserReq(removeUserReq);
                        break;

                    case Protocols.UPDATEUSER_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var updateUserReq = Serializer.Deserialize <UpdateUserReq>(stream);
                        _handler.OnUpdateUserReq(updateUserReq);
                        break;

                    case Protocols.ISDUPLICATEUSER_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var isDuplicateUserReq = Serializer.Deserialize <IsDuplicateUserReq>(stream);
                        _handler.OnIsDuplicateUserReq(isDuplicateUserReq, user);
                        break;

                    case Protocols.ONLINEUSERS_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }
                        _handler.OnOnlineUsersReq(user);
                        break;

                    case Protocols.DISCONNECTUSER_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var disconnectUserReq = Serializer.Deserialize <DisconnectUserReq>(stream);
                        _handler.OnDisconnectUserReq(disconnectUserReq);
                        break;

                    case Protocols.BANIPADDRESS_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var banIpAddressReq = Serializer.Deserialize <BanIpAddressReq>(stream);
                        _handler.OnBanIPAddressReq(banIpAddressReq, user);
                        break;

                    case Protocols.LISTBANNEDIPS_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        _handler.OnListBannedIPsReq(user);
                        break;

                    case Protocols.UNBANIPADDRESS_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var unbanIpAddressReq = Serializer.Deserialize <UnbanIPAddressReq>(stream);
                        _handler.OnUnbanIPAddressReq(unbanIpAddressReq, user);
                        break;

                    case Protocols.COMMAND_REQ:
                        if (!Guard.CheckPrivileges(user, GroupRole.Admin))
                        {
                            goto default;
                        }

                        var commandReq = Serializer.Deserialize <CommandReq>(stream);
                        _handler.OnCommandReq(commandReq, user);
                        break;

                    default:
                        // Unknown or invalid message.
                        // Increase tries and disconnecct the client
                        Guard.TryCheck(ipOnly);
                        _watsonTcpServer.DisconnectClient(ipPort);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Print out the exception and disconnect the client that might have caused it
                ConsoleKit.Message(ConsoleKit.MessageType.ERROR, e.Message + "\n" + e.StackTrace + "\n");
                _watsonTcpServer.DisconnectClient(ipPort);
            }

            return(true);
        }
示例#10
0
 /// <summary>
 /// Invoked whenever a client connects to the server
 /// </summary>
 /// <param name="ipPort"></param>
 /// <returns></returns>
 private bool ClientConnected(string ipPort)
 {
     ConsoleKit.Message(ConsoleKit.MessageType.INFO, "Client connected: {0}\n", ipPort);
     return(true);
 }