Пример #1
0
        private void Settings_FormClosing(object sender, FormClosingEventArgs e)
        {
            string CurrentRegion = Settings.IniReadValue("Settings", "Region");

            //check region if west enable login box
            if (CurrentRegion == "EN")
            {
                box_WestLogin.Visible = true;

                //if open settings with logged account play button stay enabled
                if (worker != null && worker.IsBusy)
                {
                    Btn_play.Enabled = true;
                }
                else
                {
                    btn_Login.Text    = "Login";
                    btn_Login.Enabled = true;//if change to other region and change back to NA enable login btn
                    Btn_play.Enabled  = false;
                }
            }
            else
            {
                //if not west or change region logged kill ping thread disable west login and enable play button
                if (worker != null && worker.IsBusy)
                {
                    LoginServer.Close();
                    worker.CancelAsync();
                }
                box_WestLogin.Visible = false;
                Btn_play.Enabled      = true;
            }
        }
Пример #2
0
        public void Configure()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo
                         .Console()
                         .CreateLogger();

            var config = ServerConfig.Instance;

            config.DatabaseConnectionType = DatabaseConnectionType.InMemory;
            config.DatabaseConnection     = Guid.NewGuid().ToString();
            config.AddDefaultWorld();

            Login = new LoginServer(this);

            ServerConfig.Instance.Worlds.ForEach(x =>
            {
                var world = new World(x);
                Worlds.Add(world);

                for (byte i = 0; i < x.Channels; i++)
                {
                    var game = new GameServer(this, world, ServerConfig.Instance.ChannelPort++, i);
                    world.Add(game);
                }
            });
        }
Пример #3
0
        private void OnCharacterListResponse(Packet inPacket)
        {
            string hash = inPacket.ReadString();
            User   user = LoginServer.GetUser(hash);

            if (user != null)
            {
                bool online = inPacket.ReadBool();

                if (online)
                {
                    using (Packet outPacket = new Packet(ServerMessages.SelectWorldResult))
                    {
                        outPacket.WriteByte();
                        outPacket.WriteByte(inPacket.ReadByte());
                        outPacket.WriteBytes(inPacket.ReadLeftoverBytes());

                        user.Client.Send(outPacket);
                    }
                }
                else
                {
                    using (Packet outPacket = new Packet(ServerMessages.SelectWorldResult))
                    {
                        outPacket.WriteByte(9);

                        user.Client.Send(outPacket);
                    }
                }
            }
        }
Пример #4
0
        private static void StartServers()
        {
#if DEBUG
            ServerContext.Config.DebugMode = true;
#endif

redo:
            {
                if (Errors > Config.ERRORCAP)
                {
                    Process.GetCurrentProcess().Kill();
                }

                try
                {
                    Lobby = new LoginServer(Config.ConnectionCapacity);
                    Lobby.Start(Config.LOGIN_PORT);

                    Game = new GameServer(Config.ConnectionCapacity);
                    Game.Start(DefaultPort);
                }
                catch (Exception)
                {
                    { ++DefaultPort; Errors++; }
                    goto redo;
                }
            }


            Running = true;
        }
Пример #5
0
        private void StopServer()
        {
            Server.StopServer();
            Server = null;
            (this as IController).ServerStateChanged(Utils.ServerState.STOPED);

            ServerStarted = false;

            ServerIPAddress.IsReadOnly = false;
            ServerIPPort.IsReadOnly    = false;

            UserInfoRootPath.IsReadOnly  = false;
            GroupInfoRootPath.IsReadOnly = false;
            ChatRootPath.IsReadOnly      = false;
            AppliesRootPath.IsReadOnly   = false;
            CloudRootPath.IsReadOnly     = false;
            CloudInfoRootPath.IsReadOnly = false;
            UserIDPool.IsReadOnly        = false;
            GroupIDPool.IsReadOnly       = false;

            UserSelectButton.IsEnabled      = true;
            GroupSelectButton.IsEnabled     = true;
            ChatSelectButton.IsEnabled      = true;
            AppliesSelectButton.IsEnabled   = true;
            CloudSelectButton.IsEnabled     = true;
            CloudInfoSelectButton.IsEnabled = true;
            UserIDPoolSaveButton.IsEnabled  = true;
            GroupIDPoolSaveButton.IsEnabled = true;

            StartServerButton.Content = "启动服务";
        }
Пример #6
0
        public static byte[] Encrypt(byte[] toEncrypt, byte[] key, int keyOffset)
        {
            if (key.Length <= 0 || toEncrypt.Length <= 0)
            {
                return(new byte[0]);
            }

            byte[] Out = new byte[toEncrypt.Length];
            //simple xor with key
            for (int i = 0; i < toEncrypt.Length; i++)
            {
                //Out[i] = (byte)(toEncrypt[i] ^ key[i % (key.Length / keyElementLenght)]);
                Out[i] = (byte)(toEncrypt[i] ^ key[keyOffset]);
            }
            //now xor with one char beafore
            for (int i = toEncrypt.Length - 2; i > 0; i--)
            {
                Out[i] = (byte)(Out[i] ^ Out[i + 1]);
            }
            if (Program.DEBUG_Encrypt)
            {
                string tmp = LoginServer.ByteArrayToHex(Out);
                Output.WriteLine("ENCODE WITH KEY: " + keyOffset.ToString() + " ENCODED: " + tmp);
            }
            return(Out);
        }
Пример #7
0
        private void Initialize()
        {
            this.Log("");
            this.Log("\t- WvsLogin v{0}.{1} -", Constants.MapleVersion, Constants.PatchLocation);
            this.Log("");

            try
            {
                this.Loga("Initializing Login Server... ");
                LoginServer.Initialize();
                this.Log("Done.");

                new Delay(15 * 1000, () =>
                {
                    GC.Collect(GC.MaxGeneration, GCCollectionMode.Optimized);
                }).Execute();

                this.Log("");

                this.Invoke(new MethodInvoker(() =>
                {
                    this.Text += string.Format(" ({0})", Program.ConfigurationFile);
                }));
            }
            catch (Exception e)
            {
                this.Log("Failed.");
                this.Log("");
                this.Log(e.ToString());
            }
        }
Пример #8
0
        static void Main()
        {
            Console.Title = $"Pangya Fresh UP ! LoginServer";

            Server = new LoginServer();

            Server.ServerStart();

            Server.OnPacketReceived += Server_OnPacketReceived;
            //Escuta contínuamente entradas no console (Criar comandos para o Console)
            for (;;)
            {
                var comando = Console.ReadLine().Split(new char[] { ' ' }, 2);
                switch (comando[0].ToLower())
                {
                case "": break;

                case "cls":
                case "clear":
                case "limpa":
                {
                    Console.Clear();
                }
                break;

                default:
                    Console.WriteLine("Comando inexistente");
                    break;
                }
            }
        }
        public override void ClientDisconnect(PhotonClientPeer clientPeer)
        {
            var para = new Dictionary<byte, object>
            {
                {(byte) ClientParameterCode.PeerId, clientPeer.PeerId.ToByteArray()}
            };

            if (clientPeer.ClientData<CharacterData>().CharacterId.HasValue)
            {
                Log.DebugFormat("Sending disconnect for client {0}:{1}", clientPeer.PeerId,
                    clientPeer.ClientData<CharacterData>().CharacterId.Value);
                if (ChatServer != null)
                {
                    ChatServer.SendEvent(new EventData((byte)ServerEventCode.CharacterDeRegister, para),
                   new SendParameters());
                }
                if (clientPeer.CurrentServer != null)
                {
                    clientPeer.CurrentServer.SendEvent(
                    new EventData((byte)ServerEventCode.CharacterDeRegister, para), new SendParameters());
                }
                
            }

            Log.DebugFormat("xxx sending user loggedout sendevent");
            LoginServer.SendEvent(new EventData((byte) ServerEventCode.UserLoggedOut, para), new SendParameters());
        }
Пример #10
0
        static bool Zoneupdate(LoginClient client, CMSG msgID, BinReader data)
        {
            uint newZone = (uint)data.ReadUInt32();

            client.Character.Zone  = newZone;
            client.Character.Dirty = true;
            DataServer.Database.SaveObject(client.Character);
            ScriptPacket WorldZoneUpdate = new ScriptPacket(SCRMSG.ZONEUPDATE);

            WorldZoneUpdate.Write(client.Character.ObjectId);
            WorldZoneUpdate.Write(newZone);
            client.WorldConnection.Send(WorldZoneUpdate);
            if (client.Character.OnFriends != null)
            {
                foreach (DBFriendList Friend in client.Character.OnFriends)
                {
                    LoginClient FriendOnline = LoginServer.GetLoginClientByCharacterID(Friend.Owner_ID);
                    if (FriendOnline != null)
                    {
                        BinWriter flist = LoginClient.NewPacket(SMSG.FRIEND_STATUS);
                        Chat.System(FriendOnline, client.Character.Name + "'s zone updated");
                        flist.Write((char)0x02);
                        flist.Write((ulong)client.Character.ObjectId);
                        flist.Write((int)newZone);
                        flist.Write((int)client.Character.Level);
                        flist.Write((int)client.Character.Class);
                        client.Send(flist);
                    }
                }
            }
            return(true);
        }
Пример #11
0
        private void init()
        {
            _dispatcher  = new RoomEventDispatcher();
            _roomFactory = new ServerRoomFactory(_dispatcher, _coRoutineManager, _assetManager);
            _roomManager = new SingleRoomManager(_roomFactory, _dispatcher, false, _roomListener);


            _loginServer = new LoginServer(_dispatcher, _roomManager);
            _loginServer.Start(new NetworkPortInfo(
                                   SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.BattleServer.TcpPort,
                                   SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.BattleServer.UdpPort));

            _hallServerNetwork = new HallServerNetwork(_dispatcher);
            _hallServerNetwork.StartServer(new NetworkPortInfo(
                                               SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.HallRoomServer.ListenPort, 0));

            MyHttpServer.Start(SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.HttpPort);
            if (SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.AllocationServer.Open == 1)
            {
                _hallServerNetwork.ClientConnect(new NetworkPortInfo(
                                                     SingletonManager.Get <ServerFileSystemConfigManager>().BootConfig.AllocationServer.ConnectPort, 0));
            }
            else
            {
                _logger.InfoFormat("Server Configuration: Do Not connect to Allocation Server!");
            }
        }
Пример #12
0
 public void Init()
 {
     GAME_LOGIC_URL = "https://192.168.1.16:30100/client_msg";
     _serverUrl     = "https://192.168.1.16:35000/";
     mGameServer    = new GameServer();
     _loginServer   = new LoginServer();
 }
Пример #13
0
        public JsonResult GetAnexosRequerimento(string searchPhrase, int current = 1, int rowCount = 5, int requerimentoId = 0)
        {
            if (requerimentoId != 0)
            {
                var arquivoRequerimento = new ArquivoRequerimento {
                    RequerimentoId = requerimentoId
                };
                var usuario = LoginServer.RetornarUsuarioLogado(User.Identity.Name);
                var request = FormatGridUtils <ArquivoRequerimento> .Format(Request, searchPhrase, arquivoRequerimento, current, rowCount);

                var response = new ResponseGrid <ArquivoRequerimento>();

                response = ArquivoRequerimentoServer.Listar(request, usuario);

                return(Json(new
                {
                    rows = response.Entidades,
                    current,
                    rowCount,
                    total = response.QuantidadeRegistros
                }, JsonRequestBehavior.AllowGet));
            }

            return(Json(new
            {
                rows = "",
                current,
                rowCount,
                total = 0
            }, JsonRequestBehavior.AllowGet));
        }
        private static void StartServers()
        {
#if DEBUG
            Config.DebugMode = true;
#endif
redo:
            {
                if (Errors > Config.ERRORCAP)
                {
                    Process.GetCurrentProcess().Kill();
                }

                try
                {
                    Game = new GameServer(Config.ConnectionCapacity);
                    Game.Start(DefaultPort);

                    Lobby = new LoginServer(Config.ConnectionCapacity);
                    Lobby.Start(2610);
                }
                catch (SocketException e)
                {
                    Report(e);
                    {
                        ++DefaultPort;
                        Errors++;
                    }
                    goto redo;
                }
            }
        }
Пример #15
0
        static bool TradeInvite(LoginClient client, CMSG msgID, BinReader data)
        {
            ulong inviteeGUID = data.ReadUInt64();

            uint        inviterGUID = client.Character.ObjectId;
            string      inviterNAME = client.Character.Name;
            LoginClient invitee     = LoginServer.GetLoginClientByCharacterID((uint)inviteeGUID);

            BinWriter pkga1 = LoginClient.NewPacket(SMSG.TRADE_STATUS);

            pkga1.Write((int)1);
            pkga1.Write((ulong)inviteeGUID);

            client.Send(pkga1);

            BinWriter pkgb1 = LoginClient.NewPacket(SMSG.TRADE_STATUS);

            pkgb1.Write((int)1);
            pkgb1.Write((ulong)inviterGUID);

            invitee.Send(pkgb1);

            BinWriter pkga2 = LoginClient.NewPacket(SMSG.TRADE_STATUS);

            pkga2.Write((int)2);

            client.Send(pkga2);
            invitee.Send(pkga2);

            client.Character.LastTradeID  = invitee.Character.ObjectId;
            invitee.Character.LastTradeID = client.Character.ObjectId;

            return(true);
        }
Пример #16
0
        public string Download(int file, int requerimentoId)
        {
            //string filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FileManagementPath"]);

            //string actualFilePath = System.IO.Path.Combine(filePath, file);

            var usuario      = LoginServer.RetornarUsuarioLogado(User.Identity.Name);
            var requerimento = new RequerimentoVM {
                Id = requerimentoId
            };
            var req     = ServerRequerimento.GetRequerimentoId(requerimento, usuario); // ira verrificar a permissão do download
            var arquivo = ArquivoRequerimentoServer.GetArquivo(file);

            if (req.Id == arquivo.RequerimentoId)
            {
                var actualFilePath = arquivo.Caminho;

                HttpContext.Response.ContentType = "APPLICATION/OCTET-STREAM";
                string filename = Path.GetFileName(actualFilePath);
                String Header   = "Attachment; Filename=" + filename;
                HttpContext.Response.AppendHeader("Content-Disposition", Header);
                HttpContext.Response.WriteFile(actualFilePath);
                HttpContext.Response.End();
            }
            return("");
        }
Пример #17
0
        static bool TradeGold(LoginClient client, CMSG msgID, BinReader data)
        {
            uint gold        = data.ReadUInt32();
            uint inviteeGUID = client.Character.LastTradeID;

            BinWriter pkg = LoginClient.NewPacket(SMSG.TRADE_STATUS_EXTENDED);

            pkg.Write((byte)0);                                 // 0 for giving, 1 for recieving
            pkg.Write((int)1);                                  // Message Count
            pkg.Write(gold);                                    // Money Amount
            pkg.Write((int)0);                                  // ?
            pkg.Write((int)0);                                  // ?

            client.Send(pkg);

            client.Character.TradeMoney = gold;

            LoginClient invitee = LoginServer.GetLoginClientByCharacterID((uint)inviteeGUID);

            BinWriter pkg2 = LoginClient.NewPacket(SMSG.TRADE_STATUS_EXTENDED);

            pkg2.Write((byte)1);                        // 0 for giving, 1 for recieving
            pkg2.Write((int)1);                         // Message Count
            pkg2.Write(gold);                           // Money Amount
            pkg2.Write((int)0);                         // ?
            pkg2.Write((int)0);                         // ?

            invitee.Send(pkg2);

            invitee.Character.TradeCompleted = false;

            return(true);
        }
        private static void StartServers()
        {
            Running = false;

redo:
            if (ERRORS > Config.ERRORCAP)
            {
                Process.GetCurrentProcess().Kill();
            }

            try
            {
                Lobby = new LoginServer(Config.ConnectionCapacity);
                Lobby.Start(Config.LOGIN_PORT);
                Game = new GameServer(Config.ConnectionCapacity);
                Game.Start(DEFAULT_PORT);

                Running = true;
            }
            catch (Exception)
            {
                ++DEFAULT_PORT;
                ERRORS++;
                goto redo;
            }
        }
        public ControlForm()
        {
            InitializeComponent();
            Database.ServerDatabase.InitializeSql();

            GUI = this;
            CheckForIllegalCrossThreadCalls = false;

            foreach (var sob in Database.ServerDatabase.Context.SOB.GetSOBByMap(1039))
            {
                if (sob.Mesh / 10 % 3 == 0)
                {
                    sob.Level = (byte)(20 + (sob.Mesh - 427) / 30 * 5);
                    Database.ServerDatabase.Context.SOB.AddOrUpdate(sob);
                }
            }

            SettingsReader.Read();

            //Begin login server
            Login = new LoginServer("AuthServer", Constants.LOGIN_PORT);

            //Begin game server
            Game = new GameServer("GameServer", Constants.GAME_PORT);

            //GUI Update
            Text += " - " + Constants.SERVER_NAME;
            Console.WriteLine(Constants.SERVER_NAME + " Ready to log in");
        }
Пример #20
0
        public IActionResult GetAutentificacion([FromBody] LoginServer oLoginServer)
        {
            IActionResult response = Unauthorized();

            if (oLoginServer.Usuario == null || oLoginServer.Contrasenia == null)
            {
                return(NotFound("Usuario no encontrado"));
            }
            if (oLoginServer.ValidaInicioSesion())
            {
                //oLoginResponse = new LoginResponse();
                PEMUsuarioResponse oUsuario = null;
                using (ILoginDominio oDominio = new LoginDominio())
                {
                    oUsuario = oDominio.TraerUsuario(oLoginServer.Usuario, oLoginServer.Contrasenia);
                }
                if (oUsuario != null)
                {
                    var tokenStr = GenerarTokenJwt.GenerarteTokenJwt(oUsuario);
                    response = Ok(new { token = tokenStr.TokenJwt });
                }
            }
            else
            {
                response = NotFound("Inicio de Sesion Fallido.");
            }
            return(response);
        }
Пример #21
0
        public JsonResult Salvar(FormularioValidacaoUC formularioValidacaoUC, string arquivosDeletados)
        {
            var files = Request.Files;


            var model = new FormularioValidacaoUCVM();

            try
            {
                formularioValidacaoUC.UsuarioRequerenteId = LoginServer.RetornarUsuarioLogado(User.Identity.Name).Id;
                if (formularioValidacaoUC.Id != 0)
                {
                    formularioValidacaoUC       = FormularioValidacaoUCServer.Atualizar(formularioValidacaoUC, files, Server, arquivosDeletados);
                    model.FormularioValidacaoUC = formularioValidacaoUC;
                    model.Consistencia.Add("Alterado com sucesso! Protocolo: " + formularioValidacaoUC.Protocolo, ConsisteUtils.Tipo.Sucesso);
                }
                else
                {
                    FormularioValidacaoUCServer.Novo(formularioValidacaoUC, files, Server);
                    model.Consistencia.Add("Incluido com sucesso! Protocolo: " + formularioValidacaoUC.Protocolo, ConsisteUtils.Tipo.Sucesso);
                    model.FormularioValidacaoUC = new FormularioValidacaoUC();
                }
            }
            catch (Exception e)
            {
                model.FormularioValidacaoUC = formularioValidacaoUC;
                var consistencia = new ConsisteUtils();
                consistencia.Add(e.Message, ConsisteUtils.Tipo.Inconsistencia);
                model.Consistencia = consistencia;
            }

            return(Json(model.Consistencia, JsonRequestBehavior.AllowGet));
        }
Пример #22
0
            static bool OnGuildInvite(LoginClient client, CMSG msgID, BinReader data)
            {
                DBGuild guild = client.Character.Guild;

                if (guild == null || client.Character.GuildID == 0)
                {
                    SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD);
                    return(true);
                }

                if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.INVITE) != (uint)GUILDFLAGS.INVITE)
                {
                    SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS);
                    ; return(true);
                }

                string name = data.ReadString();

                DBCharacter character = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), name.ToLower());

                if (character == null)
                {
                    SendResult(client, 1, name, (int)GUILDRESULT.NOT_FOUND);
                }

                else
                {
                    LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(character.ObjectId);
                    if (targetClient != null)
                    {
//						targetClient.Character.LastGuildID=client.Character.GuildID;
                        if (targetClient.Character.LastGuildInviterID != 0)
                        {
                            SendResult(client, 1, name, (int)GUILDRESULT.ALREADY_INVITED_TO_GUILD_S);
                            return(true);
                        }

                        if (targetClient.Character.GuildID != 0)
                        {
                            SendResult(client, 1, targetClient.Character.Name, (int)GUILDRESULT.ALREADY_IN_GUILD_S);
                            return(true);
                        }

                        targetClient.Character.LastGuildInviterID = client.Character.ObjectId;

                        BinWriter gpkg = LoginClient.NewPacket(SMSG.GUILD_INVITE);
                        gpkg.Write(client.Character.Name);
                        gpkg.Write(guild.Name);
                        targetClient.Send(gpkg);
                        SendResult(client, 1, name, (int)GUILDRESULT.SUCCESS);
                    }
                    else
                    {
                        Chat.System(client, name + " is not currently online");
                    }
                }

                return(true);
            }            //OnGuildInvite
Пример #23
0
        static void Main(string[] args)
        {
            Action <string, string> log = (category, message) => {
                lock (_lock) {
                    Log(String.Format("[{0}] {1}", category, message));
                }
            };

            Action <string, string> logError = (category, message) => {
                lock (_lock) {
                    LogError(String.Format("[{0}] {1}", category, message));
                }
            };

            IPAddress bind = IPAddress.Any;

            if (args.Length >= 1)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].Equals("+bind"))
                    {
                        if ((i >= args.Length - 1) || !IPAddress.TryParse(args[i + 1], out bind))
                        {
                            LogError("+bind value must be a valid IP Address to bind to!");
                        }
                    }
                    else if (args[i].Equals("+db"))
                    {
                        if ((i >= args.Length - 1))
                        {
                            LogError("+db value must be a path to the database");
                        }
                        else
                        {
                            LoginDatabase.Initialize(args[i + 1], log, logError);
                        }
                    }
                }
            }

            if (!LoginDatabase.IsInitialized())
            {
                LogError("Error initializing database, please confirm parameter +db is valid");
                LogError("Press any key to continue");
                Console.ReadKey();
                return;
            }

            CDKeyServer        cdKeyServer        = new CDKeyServer(bind, 29910, log, logError);
            ServerListReport   serverListReport   = new ServerListReport(bind, 27900, log, logError);
            ServerListRetrieve serverListRetrieve = new ServerListRetrieve(bind, 28910, serverListReport, log, logError);
            LoginServer        loginServer        = new LoginServer(bind, 29900, 29901, log, logError);

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Пример #24
0
    private void WriteOwnerData(NetStream stream)
    {
        string s = LoginServer.GetAccount(View.Controllers[0].Endpoint).baseModel;

        stream.WriteString(s);
        stream.WriteVector3(transform.position);
        stream.WriteString(character.id);
    }
Пример #25
0
        public ServerProgram()
        {
            EzServerConfig loginConfig = ReadConfig("login.json");
            EzServerConfig worldConfig = ReadConfig("world.json");

            _loginServer = new LoginServer(loginConfig);
            _worldServer = new WorldServer(worldConfig);
        }
Пример #26
0
 public AdminWebFront(string password, World world, InventoryCache inventoryCache, LoginServer userserver)
 {
     _inventoryCache = inventoryCache;
     _userServer     = userserver;
     m_world         = world;
     passWord        = password;
     LoadAdminPage();
 }
Пример #27
0
 private void OnLoginValidated(LoginValidatedPacket loginSuccessPacket)
 {
     Debug.Log("Login request has been validated on the Login Server: " + loginSuccessPacket.SessionKey);
     LoginServer.Disconnect();
     _cachedLoginSuccessPacket = loginSuccessPacket;
     OnLoginServerValidated?.Invoke(loginSuccessPacket);
     _clientLogic.Connect(ClientLogic.IP, ClientLogic.GAME_SERVER_PORT);
 }
Пример #28
0
        public static void Main(string[] args)
        {
            // No DI here because MapleServer is static
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info($"MapleServer started with {args.Length} args: {string.Join(", ", args)}");

            IContainer loginContainer = LoginContainerConfig.Configure();

            using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope();
            LoginServer loginServer = loginScope.Resolve <LoginServer>();

            loginServer.Start();

            IContainer gameContainer = GameContainerConfig.Configure();

            using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope();
            gameServer = gameScope.Resolve <GameServer>();
            gameServer.Start();

            // Input commands to the server
            while (true)
            {
                string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2);
                switch (input[0])
                {
                case "exit":
                case "quit":
                    gameServer.Stop();
                    loginServer.Stop();
                    return;

                case "send":
                    string       packet  = input[1].Replace(" ", "");
                    PacketWriter pWriter = new PacketWriter();
                    pWriter.Write(packet.ToByteArray());
                    logger.Info(pWriter);

                    foreach (Session session in GetSessions(loginServer, gameServer))
                    {
                        logger.Info($"Sending packet to {session}: {pWriter}");
                        session.Send(pWriter);
                    }

                    break;

                case "resolve":
                    PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]);
                    GameSession             first    = gameServer.GetSessions().Single();
                    resolver.Start(first);
                    break;

                default:
                    logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}");
                    break;
                }
            }
        }
Пример #29
0
        private static void Init(Connection pConn, byte[] data)
        {
            UInt16 realL = BitConverter.ToUInt16(data, 0);

            if (Program.DEBUG_recv_stage1 || Program.DEBUG_recv)
            {
                Output.WriteLine("Init packet recv");
            }
            if (pConn.client.Status != Client.STATUS.Connected)
            {
                if (Program.DEBUG_recv)
                {
                    Output.WriteLine("RecvPacketHandlers::Init - STATUS != CONNECTED, close connection");
                }
                pConn.Close();
                return;
            }
            if (realL != 7424)//to get real length need to swap bytes
            {
                if (Program.DEBUG_recv)
                {
                    Output.WriteLine("RecvPacketHandlers::Init - Wrong packet size, close connection");
                }
                pConn.Close();
                return;
            }
            if (data[Program.receivePrefixLength + 0] != 0x01 || data[Program.receivePrefixLength + 4] != 0x00 || data[Program.receivePrefixLength + 9] != 0x54 || data[Program.receivePrefixLength + 14] != 0x01)
            {
                if (Program.DEBUG_recv)
                {
                    Output.WriteLine("RecvPacketHandlers::Init - Wrong packet data, close connection");
                }
                pConn.Close();
                return;
            }
            int sKeyTmp = Program.rnd.Next(pConn.client.PrivateKey.Length);// random send key

            if (sKeyTmp >= pConn.client.PrivateKey.Length)
            {
                sKeyTmp = 0;
            }
            int rKeyTmp = Program.rnd.Next(pConn.client.PrivateKey.Length);//random recv key

            if (rKeyTmp >= pConn.client.PrivateKey.Length)
            {
                rKeyTmp = 0;
            }
            pConn.Send(new SendPacketHandlers.SendKey1(Program.mainKey, sKeyTmp, rKeyTmp));
            pConn.client.SendKeyOffset = sKeyTmp;
            pConn.client.RecvKeyOffset = rKeyTmp;
            pConn.client.PrivateKey    = Program.mainKey;
            if (Program.DEBUG_recv)
            {
                Output.WriteLine("RecvPacketHandlers::Init KEY: " + LoginServer.ByteArrayToHex(pConn.client.PrivateKey) + " SEND KEY OFFSET: " + sKeyTmp.ToString() + " RECV KEY OFFSET: " + rKeyTmp.ToString());
            }
            pConn.client.Status = Client.STATUS.Login;
            return;
        }
Пример #30
0
        // Testing Stuff outside of a main arg
        private static IEnumerable <Session> GetSessions(LoginServer loginServer, GameServer gameServer)
        {
            List <Session> sessions = new List <Session>();

            sessions.AddRange(loginServer.GetSessions());
            sessions.AddRange(gameServer.GetSessions());

            return(sessions);
        }
Пример #31
0
        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        private static bool InitializeServerInstance()
        {
            loginServer = Container.GetInstance<LoginServer>();

            int Port = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);
            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    loginServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    loginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }

                loginServer.MaximumPendingConnections = 100;
            }
            catch (Exception e)
            {
                Console.WriteLine(locales.ErrorIPAddressParseFailed);
                Console.Write(e.Message);
                Console.ReadKey();
                return false;
            }

            return true;
        }
Пример #32
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        private static void Main(string[] args)
        {
            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/LoginEngineLog.txt", LogLevel.Trace);

            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException += Handler.UnobservedTaskException;

            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            var ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();

            // Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;
            loginServer = Container.GetInstance<LoginServer>();
            bool TCPEnable = true;
            bool UDPEnable = false;
            int Port = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);
            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    loginServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    loginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            // TODO: ADD More Handlers.
            loginServer.MaximumPendingConnections = 100;

            #region Console Commands

            // Andyzweb: Added checks for start and stop
            // also added a running command to return status of the server
            // and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            loginServer.Start(TCPEnable, UDPEnable);
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = string.Empty;
                while (temp != consoleCommand)
                {
                    temp = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }

                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                    case "start":
                        if (loginServer.IsRunning)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            ct.TextRead("loginisrunning.txt");
                            Console.ResetColor();
                            break;
                        }

                        loginServer.Start(TCPEnable, UDPEnable);
                        break;
                    case "stop":
                        if (!loginServer.IsRunning)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            ct.TextRead("loginisnotrunning.txt");
                            Console.ResetColor();
                            break;
                        }

                        loginServer.Stop();
                        break;
                    case "exit":
                        Process.GetCurrentProcess().Kill();
                        break;
                    case "running":
                        if (loginServer.IsRunning)
                        {
                            // Console.WriteLine("Login Server is running");
                            ct.TextRead("loginisrunning.txt");
                            break;
                        }

                        // Console.WriteLine("Login Server not running");
                        ct.TextRead("loginisnotrunning.txt");
                        break;

                    #region Help Commands....

                    case "help":
                        ct.TextRead("logincmdhelp.txt");
                        break;
                    case "help start":
                        ct.TextRead("helpstart.txt");
                        break;
                    case "help exit":
                        ct.TextRead("helpstop.txt");
                        break;
                    case "help running":
                        ct.TextRead("loginhelpcmdrunning.txt");
                        break;
                    case "help Adduser":
                        ct.TextRead("logincmdadduserhelp.txt");
                        break;
                    case "help setpass":
                        ct.TextRead("logincmdhelpsetpass.txt");
                        break;

                    #endregion

                    default:

                        #region Adduser

                        // This section handles the command for adding a user to the database
                        if (consoleCommand.ToLower().StartsWith("adduser"))
                        {
                            string[] parts = consoleCommand.Split(' ');
                            if (parts.Length < 9)
                            {
                                Console.WriteLine(
                                    "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                                break;
                            }

                            string username = parts[1];
                            string password = parts[2];
                            int numChars = 0;
                            try
                            {
                                numChars = int.Parse(parts[3]);
                            }
                            catch
                            {
                                Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                                break;
                            }

                            int expansions = 0;
                            try
                            {
                                expansions = int.Parse(parts[4]);
                            }
                            catch
                            {
                                Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                                break;
                            }

                            if (expansions < 0 || expansions > 2047)
                            {
                                Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                                break;
                            }

                            int gm = 0;
                            try
                            {
                                gm = int.Parse(parts[5]);
                            }
                            catch
                            {
                                Console.WriteLine("Error: <GM Level> must be number (duh!)");
                                break;
                            }

                            string email = parts[6];
                            if (email == null)
                            {
                                email = string.Empty;
                            }

                            if (!TestEmailRegex(email))
                            {
                                Console.WriteLine("Error: <Email> You must supply an email address for this account");
                                break;
                            }

                            string firstname = parts[7];
                            try
                            {
                                if (firstname == null)
                                {
                                    throw new ArgumentNullException();
                                }
                            }
                            catch
                            {
                                Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                                break;
                            }

                            string lastname = parts[8];
                            try
                            {
                                if (lastname == null)
                                {
                                    throw new ArgumentNullException();
                                }
                            }
                            catch
                            {
                                Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                                break;
                            }

                            DBLoginData login = new DBLoginData
                                                    {
                                                        Username=username,
                                                        AccountFlags = 0,
                                                        Allowed_Characters = numChars,
                                                        CreationDate = DateTime.Now,
                                                        Email = email,
                                                        Expansions = expansions,
                                                        FirstName = firstname,
                                                        LastName = lastname,
                                                        GM = gm,
                                                        Flags = 0,
                                                        Password = new LoginEncryption().GeneratePasswordHash(password)
                                                    };
                            try
                            {
                                LoginDataDao.WriteLoginData(login);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(
                                    "An error occured while trying to add a new user account:\n{0}", ex.Message);
                                break;
                            }

                            Console.WriteLine("User added successfully.");
                            break;
                        }

                        #endregion

                        #region Hashpass

                        // This function just hashes the string you enter using the loginencryption method
                        if (consoleCommand.ToLower().StartsWith("hash"))
                        {
                            string Syntax =
                                "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                            string[] parts = consoleCommand.Split(' ');
                            if (parts.Length != 2)
                            {
                                Console.WriteLine(Syntax);
                                break;
                            }

                            string pass = parts[1];
                            var le = new LoginEncryption();
                            string hashed = le.GeneratePasswordHash(pass);
                            Console.WriteLine(hashed);
                            break;
                        }

                        #endregion

                        #region setpass

                        // sets the password for the given username
                        // Added by Andyzweb
                        // Still TODO add exception and error handling
                        if (consoleCommand.ToLower().StartsWith("setpass"))
                        {
                            string Syntax =
                                "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                            string[] parts = consoleCommand.Split(' ');
                            if (parts.Length != 3)
                            {
                                Console.WriteLine(Syntax);
                                break;
                            }

                            string username = parts[1];
                            string newpass = parts[2];
                            var le = new LoginEncryption();
                            string hashed = le.GeneratePasswordHash(newpass);

                            try
                            {
                                LoginDataDao.WriteNewPassword(
                                    new DBLoginData { Username = username, Password = hashed });
                            }
                                // yeah this part here, some kind of exception handling for mysql errors
                            catch (Exception ex)
                            {
                                Console.WriteLine("Could not set new Password\r\n"+ex.Message);
                                LogUtil.ErrorException(ex);
                            }
                        }

                        #endregion

                        ct.TextRead("login_consolecmdsdefault.txt");
                        break;
                }
            }

            #endregion
        }