private static void ValidateSshServer(SshServer server)
        {
            if (server.SshPort <= 0)
            {
                throw new ValidateException("SshPort", "You need a SSH port!");
            }

            if (string.IsNullOrEmpty(server.SshUsername))
            {
                throw new ValidateException("SshUsername", "You need a username!");
            }

            if (string.IsNullOrEmpty(server.SshPassword) && (server.SshKeyFileName == null || !server.SshKeyFileName.Any()))
            {
                throw new ValidateException("SshPassword", "You need at least a password or a key file!");
            }

            if (server.SshUsername == "root")
            {
                throw new ValidateException("SshUsername", "Dont use root here!");
            }

            try
            {
                RconStatic.AuthenticateOnTheSshServer(server);
            }
            catch (CommandException e)
            {
                throw new ValidateException("Id", e.Message);
            }
        }
Example #2
0
        public bool SaveBlackListEntry(PavlovServer server, List <ServerBans> NewBlackListContent)
        {
            var blacklistArray = NewBlackListContent.Select(x => x.SteamId).ToArray();

            RconStatic.WriteFile(server.SshServer, server.ServerFolderPath + FilePaths.BanList, blacklistArray, _notifyService);
            return(true);
        }
Example #3
0
        public async Task <IActionResult> StopAndTakeAway(string apiKey, int sshServerId, int pavlovServerId)
        {
            if (!HasAccess(apiKey))
            {
                return(BadRequest("No AuthKey set or wrong auth key!"));
            }
            var sshServer = await _sshServerSerivce.FindOne(sshServerId);

            var pavlovServer = await _pavlovServerService.FindOne(pavlovServerId);

            if (sshServer == null)
            {
                return(BadRequest("The ssh server does not exist!"));
            }
            if (!sshServer.IsForHosting)
            {
                return(BadRequest("The ssh server ist not for hosting!"));
            }
            await RconStatic.SystemDStop(pavlovServer, _pavlovServerService);

            pavlovServer.OldOwner = pavlovServer.Owner;
            pavlovServer.Owner    = null;
            await _pavlovServerService.Upsert(pavlovServer);

            return(Ok());
        }
        public async Task <IActionResult> GetServerLog(int serverId)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = await _pavlovServerService.FindOne(serverId);

            try
            {
                var connectionResult = await RconStatic.GetServerLog(server, _pavlovServerService);

                if (connectionResult.Success)
                {
                    var replace = connectionResult.answer.Replace("\n", "<br/>");
                    return(View("ServerLogs", replace));
                }
                else
                {
                    return(BadRequest("Coud not get data:" + connectionResult.errors));
                }
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }
        }
Example #5
0
        private async Task <bool> SaveToFile(PavlovServer pavlovServer, List <string> steamIds)
        {
            var lines = steamIds.Select(steamIdentity => steamIdentity).ToList();

            RconStatic.WriteFile(pavlovServer.SshServer, pavlovServer.ServerFolderPath + FilePaths.ModList, lines.ToArray(),
                                 _notifyService);
            return(true);
        }
        private async Task <PavlovServer> HasToStop(PavlovServer pavlovServer, bool hasToStop, bool root)
        {
            if (hasToStop)
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("stop server again!", LogEventLevel.Verbose,
                                                                _notifyService);
                await RconStatic.SystemDStop(pavlovServer, this);

                pavlovServer = await GetServerServiceState(pavlovServer);
            }

            return(pavlovServer);
        }
        public async Task <IActionResult> StopSystemdService(int serverId)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = await _pavlovServerService.FindOne(serverId);

            try
            {
                await RconStatic.SystemDStop(server, _pavlovServerService);
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
Example #8
0
        public async Task DeleteAllUnsedMapsFromAllServers()
        {
            var servers = await _sshServerSerivce.FindAll();

            foreach (var server in servers)
            {
                foreach (var signleServer in server.PavlovServers)
                {
                    try
                    {
                        RconStatic.DeleteUnusedMaps(signleServer,
                                                    (await _serverSelectedMapService.FindAllFrom(signleServer)).ToList());
                    }
                    catch (Exception e)
                    {
                        DataBaseLogger.LogToDatabaseAndResultPlusNotify(e.Message, LogEventLevel.Verbose, _notifyService);
                        // ingore for now
                    }
                }
            }
        }
        public async Task <IActionResult> UpdatePavlovServer(int serverId)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = await _pavlovServerService.FindOne(serverId);

            var result = "";

            try
            {
                result = await RconStatic.UpdateInstallPavlovServer(server, _pavlovServerService);
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }

            return(new ObjectResult(result));
        }
        /// <summary>
        /// </summary>
        /// <param name="pavlovServer"></param>
        /// <param name="rconService"></param>
        /// <returns></returns>
        public async Task <PavlovServer> GetServerServiceState(PavlovServer pavlovServer)
        {
            var state = await RconStatic.SystemDCheckState(pavlovServer, _notifyService);

            // state can be: active, inactive,disabled
            if (state == "active")
            {
                pavlovServer.ServerServiceState = ServerServiceState.active;
            }
            else if (state == "inactive")
            {
                pavlovServer.ServerServiceState = ServerServiceState.inactive;
            }
            else if (state == "disabled")
            {
                pavlovServer.ServerServiceState = ServerServiceState.disabled;
            }
            else
            {
                pavlovServer.ServerServiceState = ServerServiceState.none;
            }

            return(pavlovServer);
        }
        public async Task <ConnectionResult> StartMatchWithAuth(RconService.AuthType authType,
                                                                PavlovServer server,
                                                                Match match)
        {
            var connectionInfo = RconStatic.ConnectionInfoInternal(server.SshServer, authType, out var result);

            using var clientSsh  = new SshClient(connectionInfo);
            using var clientSftp = new SftpClient(connectionInfo);
            try
            {
                var listOfSteamIdentietiesWhichCanPlay = match.MatchTeam0SelectedSteamIdentities;
                listOfSteamIdentietiesWhichCanPlay.AddRange(match.MatchTeam1SelectedSteamIdentities);
                var list = new List <string>();
                if (listOfSteamIdentietiesWhichCanPlay.Count <= 0 && match.MatchSelectedSteamIdentities.Count <= 0)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("There are no team members so no match will start!",
                                                                    LogEventLevel.Fatal, _notifyService, result);
                    return(result);
                }


                if (match.MatchSelectedSteamIdentities.Count > 0)
                {
                    list = match.MatchSelectedSteamIdentities
                           .Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }
                else if (listOfSteamIdentietiesWhichCanPlay.Count > 0)
                {
                    list = listOfSteamIdentietiesWhichCanPlay.Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }

                list = list.Distinct().ToList();
                //GetAllAdminsForTheMatch
                var mods = new List <string>();
                //Todo what if the match is not team based? there are no mods or admins?
                mods = listOfSteamIdentietiesWhichCanPlay.Where(x => x.OverWriteRole == "Mod" || x.OverWriteRole == "Admin").Select(x => x.SteamIdentityId).ToList();


                //Write whitelist and set server settings


                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.WhiteList,
                                     list.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.ModList,
                                     mods.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.BanList,
                                     Array.Empty <string>(), _notifyService);


                var oldSettings = new PavlovServerGameIni();
                oldSettings.ReadFromFile(server, _notifyService);

                var serverSettings = new PavlovServerGameIni
                {
                    bEnabled        = true,
                    ServerName      = match.Name,
                    MaxPlayers      = match.PlayerSlots,
                    bSecured        = true,
                    bCustomServer   = true,
                    bWhitelist      = true,
                    RefreshListTime = 120,
                    LimitedAmmoType = 0,
                    TickRate        = 90,
                    TimeLimit       = match.TimeLimit,
                    Password        = "",
                    BalanceTableURL = "",
                    bVerboseLogging = true,
                    bCompetitive    = true,
                    MapRotation     = new List <PavlovServerGameIniMap>
                    {
                        new()
                        {
                            MapLabel = match.MapId,
                            GameMode = match.GameMode
                        }
                    },
                    ApiKey = oldSettings.ApiKey
                };
                var map = await _mapsService.FindOne(match.MapId.Replace("UGC", ""));

                serverSettings.SaveToFile(server, new[]
                {
                    new ServerSelectedMap()
                    {
                        Map      = map,
                        GameMode = match.GameMode
                    }
                }, _notifyService);
                await RconStatic.SystemDStart(server, _pavlovServerService);

                //StartWatchServiceForThisMatch
                match.Status = Status.StartetWaitingForPlayer;
                await Upsert(match);

                DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start backgroundjob", LogEventLevel.Verbose,
                                                                _notifyService);

                BackgroundJob.Enqueue(
                    () => MatchInspector(match.Id)); // ChecjServerState
            }
        public async Task RemovePavlovServerFromDisk(
            PavlovServerViewModel server, bool ignoreMostExceptions)
        {
            //Todo AuthError??
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start remove server!", LogEventLevel.Verbose,
                                                            _notifyService);
            string result = "";

            //start server and stop server to get Saved folder etc.
            if (ignoreMostExceptions)
            {
                try
                {
                    await RconStatic.SystemDStop(server, _pavlovServerService);
                }
                catch (CommandException)
                {
                    //ignore
                }
            }
            else
            {
                await RconStatic.SystemDStop(server, _pavlovServerService);
            }

            if (ignoreMostExceptions)
            {
                try
                {
                    await RconStatic.RemovePath(server, server.ServerFolderPath, _pavlovServerService);
                }
                catch (CommandException)
                {
                    //ignore
                }
            }
            else
            {
                await RconStatic.RemovePath(server, server.ServerFolderPath, _pavlovServerService);
            }


            server.SshServer = await FindOne(server.sshServerId);

            if (server.SshServer == null)
            {
                throw new CommandException("Could not get the sshServer!");
            }
            var oldSSHcrid = new SshServer
            {
                SshPassphrase  = server.SshServer.SshPassphrase,
                SshUsername    = server.SshServer.SshUsername,
                SshPassword    = server.SshServer.SshPassword,
                SshKeyFileName = server.SshServer.SshKeyFileName
            };

            server.SshServer.SshPassphrase = server.SshPassphraseRoot;
            server.SshServer.SshUsername   = server.SshUsernameRoot;
            server.SshServer.SshPassword   = server.SshPasswordRoot;
            if (server.SshKeyFileNameForm != null)
            {
                await using var ms = new MemoryStream();
                await server.SshKeyFileNameForm.CopyToAsync(ms);

                var fileBytes = ms.ToArray();
                server.SshKeyFileNameRoot = fileBytes;
                // act on the Base64 data
            }
            server.SshServer.SshKeyFileName     = server.SshKeyFileNameRoot;
            server.SshServer.NotRootSshUsername = oldSSHcrid.SshUsername;


            if (ignoreMostExceptions)
            {
                try
                {
                    await RconStatic.RemovePath(server,
                                                "/etc/systemd/system/" + server.ServerSystemdServiceName + ".service", _pavlovServerService);
                }
                catch (CommandException)
                {
                    //ignore
                }
            }
            else
            {
                await RconStatic.RemovePath(server,
                                            "/etc/systemd/system/" + server.ServerSystemdServiceName + ".service", _pavlovServerService);
            }

            //Remove the server from the sudoers file
            var sudoersPathParent = "/etc/sudoers.d";
            var sudoersPath       = sudoersPathParent + "/pavlovRconWebserverManagement";
            var removed           = true;


            if (ignoreMostExceptions)
            {
                try
                {
                    removed = RconStatic.RemoveServerLineToSudoersFile(server, _notifyService, sudoersPath, _pavlovServerService);
                }
                catch (CommandException)
                {
                    //ignore
                }
            }
            else
            {
                removed = RconStatic.RemoveServerLineToSudoersFile(server, _notifyService, sudoersPath, _pavlovServerService);
            }
            if (removed)
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("server line removed from sudoers file!",
                                                                LogEventLevel.Verbose, _notifyService);
            }
            else
            {
                //means that the lines still is in the file!!!
                var error =
                    "Could not remove the server line from sudoers file!";
                DataBaseLogger.LogToDatabaseAndResultPlusNotify(error, LogEventLevel.Fatal, _notifyService);
                if (!ignoreMostExceptions)
                {
                    throw new CommandException(error);
                }
            }

            //Handle the presets an newer systemd
            if (ignoreMostExceptions)
            {
                try
                {
                    RconStatic.AddLineToNewerSystemDsIfNeeded(server, _notifyService, true);
                }
                catch (CommandException)
                {
                    //ignore
                }
            }
            else
            {
                RconStatic.AddLineToNewerSystemDsIfNeeded(server, _notifyService, true);
            }



            DataBaseLogger.LogToDatabaseAndResultPlusNotify(result, LogEventLevel.Verbose, _notifyService);
        }
Example #13
0
        /// <summary>
        /// Return back if the server should forceStop
        /// </summary>
        /// <param name="server"></param>
        /// <param name="match"></param>
        /// <returns></returns>
        /// <exception cref="CommandException"></exception>
        public async Task <bool> SShTunnelGetAllInfoFromPavlovServer(PavlovServer server, Match match = null)
        {
            var result        = RconStatic.StartClient(server, out var client);
            var costumesToSet = new Dictionary <string, string>();

            try
            {
                client.Connect();

                if (client.IsConnected)
                {
                    var nextFreePort  = RconStatic.GetAvailablePort();
                    var portToForward = nextFreePort;
                    var portForwarded = new ForwardedPortLocal("127.0.0.1", (uint)portToForward, "127.0.0.1",
                                                               (uint)server.TelnetPort);
                    client.AddForwardedPort(portForwarded);
                    portForwarded.Start();
                    using (var client2 = new Client("127.0.0.1", portToForward, new CancellationToken()))
                    {
                        if (client2.IsConnected)
                        {
                            var password = await client2.ReadAsync(TimeSpan.FromMilliseconds(2000));

                            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Answer: " + password,
                                                                            LogEventLevel.Verbose, _notifyService);
                            if (password.ToLower().Contains("password"))
                            {
                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("start sending password!",
                                                                                LogEventLevel.Verbose, _notifyService);
                                await client2.WriteLine(server.TelnetPassword);

                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("did send password and wait for auth",
                                                                                LogEventLevel.Verbose, _notifyService);

                                var auth = await client2.ReadAsync(TimeSpan.FromMilliseconds(2000));

                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("waited for auth get : " + auth,
                                                                                LogEventLevel.Verbose, _notifyService);
                                if (auth.ToLower().Contains("authenticated=1"))
                                {
                                    // it is authetificated
                                    var commandOne           = "RefreshList";
                                    var singleCommandResult1 =
                                        await RconStatic.SingleCommandResult(client2, commandOne);

                                    var playersList =
                                        JsonConvert.DeserializeObject <PlayerListClass>(singleCommandResult1);
                                    var steamIds = playersList?.PlayerList.Select(x => x.UniqueId);
                                    //Inspect PlayerList
                                    var commands = new List <string>();
                                    if (steamIds != null)
                                    {
                                        foreach (var steamId in steamIds)
                                        {
                                            commands.Add("InspectPlayer " + steamId);
                                        }
                                    }

                                    var playerListRaw = new List <string>();
                                    foreach (var command in commands)
                                    {
                                        var commandResult = await RconStatic.SingleCommandResult(client2, command);

                                        playerListRaw.Add(commandResult);
                                    }

                                    var playerListJson = string.Join(",", playerListRaw);
                                    playerListJson = "[" + playerListJson + "]";
                                    var finsihedPlayerList = new List <PlayerModelExtended>();
                                    var tmpPlayers         = JsonConvert.DeserializeObject <List <PlayerModelExtendedRconModel> >(
                                        playerListJson, new JsonSerializerSettings {
                                        CheckAdditionalContent = false
                                    });
                                    var steamIdentities = (await _steamIdentityService.FindAll()).ToList();

                                    if (tmpPlayers != null)
                                    {
                                        foreach (var player in tmpPlayers)
                                        {
                                            player.PlayerInfo.Username = player.PlayerInfo.PlayerName;
                                            var identity =
                                                steamIdentities?.FirstOrDefault(x =>
                                                                                x.Id == player.PlayerInfo.UniqueId);
                                            if (identity != null && (identity.Costume != "None" ||
                                                                     !string.IsNullOrEmpty(identity.Costume)))
                                            {
                                                if (server.Shack)
                                                {
                                                    costumesToSet.Add(identity.OculusId, identity.Costume);
                                                }
                                                else
                                                {
                                                    costumesToSet.Add(identity.Id, identity.Costume);
                                                }
                                            }
                                        }

                                        finsihedPlayerList = tmpPlayers.Select(x => x.PlayerInfo).ToList();
                                    }

                                    var pavlovServerPlayerList = finsihedPlayerList.Select(x =>
                                    {
                                        var player      = new PavlovServerPlayer();
                                        player.Username = x.Username;
                                        player.UniqueId = x.UniqueId;
                                        player.KDA      = x.KDA;
                                        player.Cash     = x.Cash;
                                        player.TeamId   = x.TeamId;
                                        player.Score    = x.Score;
                                        player.ServerId = server.Id;
                                        return(player);
                                    }).ToList();
                                    var oldServerInfo = await _pavlovServerInfoService.FindServer(server.Id);

                                    //Todo maybe check if we lost a player its possible that we need that if allstats after the end of a match doesent give back all the player if some had a disconnect
                                    await _pavlovServerPlayerService.Upsert(pavlovServerPlayerList, server.Id);

                                    await _pavlovServerPlayerHistoryService.Upsert(pavlovServerPlayerList.Select(x =>
                                    {
                                        var history = new PavlovServerPlayerHistory();
                                        history.Username = x.Username;
                                        history.UniqueId = x.UniqueId;
                                        history.PlayerName = x.PlayerName;
                                        history.KDA = x.KDA;
                                        history.Cash = x.Cash;
                                        history.TeamId = x.TeamId;
                                        history.Score = x.Score;
                                        history.ServerId = x.ServerId;
                                        history.date = DateTime.Now;
                                        return(history);
                                    }).ToList(), server.Id, 1);

                                    var singleCommandResultTwo =
                                        await RconStatic.SingleCommandResult(client2, "ServerInfo");

                                    var tmp = JsonConvert.DeserializeObject <ServerInfoViewModel>(
                                        singleCommandResultTwo.Replace("\"\"", "\"ServerInfo\""));
                                    if (tmp == null || tmp.ServerInfo == null)
                                    {
                                        return(false);
                                    }
                                    if (!string.IsNullOrEmpty(tmp.ServerInfo.GameMode))
                                    {
                                        DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                                            "Got the server info for the server: " + server.Name + "\n " +
                                            singleCommandResultTwo, LogEventLevel.Verbose, _notifyService);
                                    }


                                    tmp.ServerId = server.Id;
                                    var map = await _mapsService.FindOne(tmp.ServerInfo.MapLabel.Replace("UGC", ""));

                                    if (map != null)
                                    {
                                        tmp.ServerInfo.MapPictureLink = map.ImageUrl;
                                    }

                                    //Check of next round
                                    bool nextRound = oldServerInfo != null && oldServerInfo.MapLabel != tmp.ServerInfo.MapLabel;
                                    if (!nextRound && oldServerInfo != null && match is { Status : Status.OnGoing }) // more checks cause in a match the map is only one and will not trigger the first try
                                    {
                                        var gotResult1 = int.TryParse(oldServerInfo.Team0Score, out var oldTeam0Score);
                                        var gotResult2 = int.TryParse(oldServerInfo.Team1Score, out var oldTeam1Score);
                                        var gotResult3 = int.TryParse(tmp.ServerInfo.Team0Score, out var newTeam0Score);
                                        var gotResult4 = int.TryParse(tmp.ServerInfo.Team1Score, out var newTeam1Score);

                                        if (gotResult1 && gotResult2 && gotResult3 && gotResult4 && (
                                                oldTeam0Score > newTeam0Score ||
                                                oldTeam1Score > newTeam1Score)
                                            )
                                        {
                                            nextRound = true;
                                        }
                                    }
                                    var round = oldServerInfo?.Round ?? 0;
                                    if (nextRound)
                                    {
                                        if (round == 999)
                                        {
                                            round = 0; // reset value that's why you have to use the nextRound bool down from here to know if its the next round
                                        }

                                        round++;
                                    }

                                    if (match is { Status : Status.OnGoing } && nextRound)
        public virtual async Task <PavlovServer> ValidatePavlovServer(PavlovServer pavlovServer, bool root)
        {
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("start validate", LogEventLevel.Verbose, _notifyService);
            var hasToStop = false;

            await IsValidOnly(pavlovServer);


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to start service", LogEventLevel.Verbose,
                                                            _notifyService);
            //try if the service realy exist
            try
            {
                pavlovServer = await GetServerServiceState(pavlovServer);

                if (pavlovServer.ServerServiceState != ServerServiceState.active)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("has to start", LogEventLevel.Verbose,
                                                                    _notifyService);
                    hasToStop = true;
                    //the problem is here for the validating part if it has to start the service first it has problems
                    await RconStatic.SystemDStart(pavlovServer, this);

                    pavlovServer = await GetServerServiceState(pavlovServer);

                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("state = " + pavlovServer.ServerServiceState,
                                                                    LogEventLevel.Verbose, _notifyService);
                }
            }
            catch (CommandException e)
            {
                throw new ValidateException(e.Message);
            }

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to send serverinfo", LogEventLevel.Verbose,
                                                            _notifyService);
            //try to send Command ServerInfo
            try
            {
                await RconStatic.SendCommandSShTunnel(pavlovServer, "ServerInfo", _notifyService);
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            //try if the user have rights to delete maps cache
            try
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("delete unused maps", LogEventLevel.Verbose,
                                                                _notifyService);
                RconStatic.DeleteUnusedMaps(pavlovServer,
                                            (await _serverSelectedMapService.FindAllFrom(pavlovServer)).ToList());
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            if (!string.IsNullOrEmpty(pavlovServer.SshServer.ShackMapsPath))
            {
                try
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("check if ShackMapsPath exist!", LogEventLevel.Verbose,
                                                                    _notifyService);
                    RconStatic.DoesPathExist(pavlovServer, pavlovServer.SshServer.ShackMapsPath, _notifyService);
                }
                catch (CommandException e)
                {
                    await HasToStop(pavlovServer, hasToStop, root);

                    throw new ValidateException("ShackMapsPath does not exist: " + pavlovServer.SshServer.ShackMapsPath + "additional info:" + e.Message);
                }
            }

            await HasToStop(pavlovServer, hasToStop, root);

            return(pavlovServer);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="server"></param>
        /// <param name="reservedFor"></param>
        /// <exception cref="CommandExceptionCreateServerDuplicate"></exception>

        public async Task CreatePavlovServer(PavlovServerViewModel server, string reservedFor = "")
        {
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start creting server", LogEventLevel.Verbose,
                                                            _notifyService);
            //Check stuff
            var exist = RconStatic.DoesPathExist(server, server.ServerFolderPath, _notifyService);

            if (exist)
            {
                throw new CommandExceptionCreateServerDuplicate("ServerFolderPath already exist!");
            }

            exist = RconStatic.DoesPathExist(server,
                                             "/etc/systemd/system/" + server.ServerSystemdServiceName + ".service", _notifyService);
            if (exist)
            {
                throw new CommandExceptionCreateServerDuplicate("Systemd Service already exist!");
            }

            var portsUsed = (await FindAll()).Where(x => x.SshServer.Id == server.SshServer.Id)
                            .FirstOrDefault(x => x.ServerPort == server.ServerPort || x.TelnetPort == server.TelnetPort);

            if (portsUsed != null)
            {
                if (portsUsed.ServerPort == server.ServerPort)
                {
                    throw new CommandExceptionCreateServerDuplicate("The server port is already used!");
                }

                if (portsUsed.TelnetPort == server.TelnetPort)
                {
                    throw new CommandExceptionCreateServerDuplicate("The telnet port is already used!");
                }
            }


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start Install pavlovserver", LogEventLevel.Verbose,
                                                            _notifyService);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                "Username used befor changed to root: " + server.SshServer.SshUsername, LogEventLevel.Verbose,
                _notifyService);

            await RconStatic.UpdateInstallPavlovServer(server, this);


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start Install pavlovserver service",
                                                            LogEventLevel.Verbose, _notifyService);

            var oldSSHcrid = new SshServer
            {
                SshPassphrase  = server.SshServer.SshPassphrase,
                SshUsername    = server.SshServer.SshUsername,
                SshPassword    = server.SshServer.SshPassword,
                SshKeyFileName = server.SshServer.SshKeyFileName
            };

            server.SshServer.SshPassphrase      = server.SshPassphraseRoot;
            server.SshServer.SshUsername        = server.SshUsernameRoot;
            server.SshServer.SshPassword        = server.SshPasswordRoot;
            server.SshServer.SshKeyFileName     = server.SshKeyFileNameRoot;
            server.SshServer.NotRootSshUsername = oldSSHcrid.SshUsername;

            try
            {
                await RconStatic.InstallPavlovServerService(server, _notifyService);
            }
            catch (CommandException e)
            {
                //If crash inside here the user login is still root. If the root login is bad this will fail to remove the server afterwards
                OverwrideTheNormalSSHLoginData(server, oldSSHcrid);
                DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                    "Could not install service while creating the pavlov server -> " + e.Message, LogEventLevel.Verbose, _notifyService);
                throw;
            }
            OverwrideTheNormalSSHLoginData(server, oldSSHcrid);
            DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                "Username used after override old infos: " + server.SshServer.SshUsername, LogEventLevel.Verbose,
                _notifyService);
            //start server and stop server to get Saved folder etc.

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start after install", LogEventLevel.Verbose,
                                                            _notifyService);

            await RconStatic.SystemDStart(server, this);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("stop after install", LogEventLevel.Verbose,
                                                            _notifyService);

            await RconStatic.SystemDStop(server, this);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Try to save game ini", LogEventLevel.Verbose,
                                                            _notifyService);



            var pavlovServerGameIni = new PavlovServerGameIni();

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("created Ini", LogEventLevel.Verbose, _notifyService);
            var selectedMaps = await _serverSelectedMapService.FindAllFrom(server);

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("found maps", LogEventLevel.Verbose, _notifyService);
            pavlovServerGameIni.ServerName = server.Name;


            pavlovServerGameIni.SaveToFile(server, selectedMaps, _notifyService);

            //also create rcon settings


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("write rcon file", LogEventLevel.Verbose,
                                                            _notifyService);

            var lines = new List <string>
            {
                "Password="******"Port=" + server.TelnetPort
            };

            RconStatic.WriteFile(server.SshServer, server.ServerFolderPath + FilePaths.RconSettings,
                                 lines.ToArray(), _notifyService);
        }
Example #16
0
        public async Task <IActionResult> SendCommandMulti(int server, string command, string[] players, string value = "")
        {
            var singleServer = await _pavlovServerService.FindOne(server);

            var servers = await GiveServerWhichTheUserHasRightsTo();

            LiteDbUser user;

            user = await _userservice.getUserFromCp(HttpContext.User);

            if (!servers.Select(x => x.Id).Contains(singleServer.Id))
            {
                return(Forbid());
            }
            var isMod = await RightsHandler.IsModOnTheServer(_serverSelectedModsService, singleServer, user.Id);

            var commands = await RightsHandler.GetAllowCommands(new RconViewModel(), HttpContext.User, _userservice, isMod, singleServer, user);



            var contains = false;

            foreach (var singleCommand in commands)
            {
                if (command.Contains(singleCommand))
                {
                    contains = true;
                }
            }
            if (contains != true)
            {
                return(Forbid());
            }

            if (command.StartsWith("GodMode"))
            {
                command = "Slap";
                value   = "-2147000000";
            }
            if (command.StartsWith("CustomPlayer") || command.StartsWith("Custom"))
            {
                if (command.StartsWith("CustomPlayer"))
                {
                    var count = value.Count(x => x == ' ');
                    if (count == 1)
                    {
                        var pieces = value.Split(new[] { ' ' }, 2);
                        command = pieces[0];
                        value   = pieces[1];
                    }
                }
                else
                {
                    command = command.Substring(7);
                }
            }


            var responses = Array.Empty <string>();

            try
            {
                var commandsList = new List <string>();
                foreach (var player in players)
                {
                    if (value == null)
                    {
                        commandsList.Add(command + " " + player);
                    }
                    else
                    {
                        commandsList.Add(command + " " + player + " " + value);
                    }
                }
                responses = await RconStatic.SShTunnelMultipleCommands(singleServer, commandsList.ToArray(), _toastifyService);
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }
            if (string.IsNullOrEmpty(string.Join(";", responses)))
            {
                return(BadRequest("The response was empty!"));
            }

            var commandsResulsts = new List <string>();

            try
            {
                foreach (var response in responses)
                {
                    var tmp = JsonConvert.DeserializeObject <MinimumRconResultObject>(response, new JsonSerializerSettings {
                        CheckAdditionalContent = false
                    });
                    var o      = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(response);
                    var value3 = o.Property("")?.Value;
                    var value2 = o.Property(tmp.Command)?.Value;
                    if (tmp != null && (value3 is { HasValues: false } || value2 is { HasValues: false }))