public async Task <IActionResult> EditServer(int serverId, int sshServerId, bool create = false,
                                                     bool remove = false)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = new PavlovServer();

            if (serverId != 0)
            {
                server = await _pavlovServerService.FindOne(serverId);
            }

            if (server.SshServer == null)
            {
                server.SshServer = await _sshServerSerivce.FindOne(sshServerId);
            }

            var viewModel = new PavlovServerViewModel();

            viewModel = viewModel.fromPavlovServer(server, sshServerId);

            viewModel.LiteDbUsers = (await _userservice.FindAll()).ToList();

            viewModel.create = create;
            viewModel.remove = remove;
            return(View("Server", viewModel));
        }
 private PavlovServerViewModel OverwrideTheNormalSSHLoginData(PavlovServerViewModel server, SshServer oldSSHcrid)
 {
     server.SshServer.SshPassphrase  = oldSSHcrid.SshPassphrase;
     server.SshServer.SshUsername    = oldSSHcrid.SshUsername;
     server.SshServer.SshPassword    = oldSSHcrid.SshPassword;
     server.SshServer.SshKeyFileName = oldSSHcrid.SshKeyFileName;
     return(server);
 }
        public async Task <IActionResult> EditServer(PavlovServerViewModel server)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), server.Id, _service, _pavlovServerService))
            {
                return(Forbid());
            }

            server.LiteDbUsers = (await _userservice.FindAll()).ToList();
            return(View("Server", server));
        }
        public async Task <IActionResult> DeleteServerFromFolder(PavlovServerViewModel viewModel)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), viewModel.sshServerId, _service,
                                                                 _pavlovServerService))
            {
                return(Forbid());
            }
            try
            {
                await _service.RemovePavlovServerFromDisk(viewModel, false);
            }
            catch (CommandException e)
            {
                return(BadRequest(e.Message));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
 private async Task <IActionResult> GoBackEditServer(PavlovServerViewModel server, string error,
                                                     bool remove = false)
 {
     if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                          await _userservice.getUserFromCp(HttpContext.User), server.Id, _service, _pavlovServerService))
     {
         return(Forbid());
     }
     if (remove)
     {
         var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";
         if (!isDevelopment)
         {
             await _service.RemovePavlovServerFromDisk(server, true);
         }
     }
     ModelState.AddModelError("Id", error);
     return(await EditServer(server));
 }
예제 #6
0
        public async Task <IActionResult> RemovePavlovServer(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!"));
            }
            var viewmodel = new PavlovServerViewModel();

            viewmodel = viewmodel.fromPavlovServer(pavlovServer, sshServerId);
            //todo add admin
            viewmodel.remove             = true;
            viewmodel.SshPassphraseRoot  = sshServer.SshPassphraseRootForHosting;
            viewmodel.SshPasswordRoot    = sshServer.SshPasswordRootForHosting;
            viewmodel.SshUsernameRoot    = sshServer.SshUsernameRootForHosting;
            viewmodel.SshKeyFileNameRoot = sshServer.SshKeyFileNameRootForHosting;
            try
            {
                await _sshServerSerivce.RemovePavlovServerFromDisk(viewmodel, false);
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
            await _pavlovServerService.Delete(pavlovServer.Id);

            return(Ok());
        }
        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);
        }
        public async Task <IActionResult> SaveServer(PavlovServerViewModel server)
        {
            if (!ModelState.IsValid)
            {
                return(View("Server", server));
            }

            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), server.Id, _service, _pavlovServerService))
            {
                return(Forbid());
            }

            server.LiteDbUsers = (await _userservice.FindAll()).ToList();

            server.Owner = (await _userservice.FindAll())
                           .FirstOrDefault(x => x.Id == new ObjectId(server.LiteDbUserId));
            var resultServer = new PavlovServer();

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

            if (server.create)
            {
                // Duplicate Database entries check
                try
                {
                    await _pavlovServerService.IsValidOnly(server, false);

                    if (string.IsNullOrEmpty(server.SshServer.SshPassword))
                    {
                        throw new ValidateException("Id",
                                                    "Please add a sshPassword to the ssh user (Not root user). Sometimes the systems asks for the password even if the keyfile and passphrase is used.");
                    }
                    if (string.IsNullOrEmpty(server.ServerFolderPath))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath is needed!");
                    }
                    if (!server.ServerFolderPath.EndsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the end!");
                    }
                    if (!server.ServerFolderPath.StartsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the start!");
                    }
                    if (server.ServerPort <= 0)
                    {
                        throw new ValidateException("ServerPort", "The server port is needed!");
                    }
                    if (server.TelnetPort <= 0)
                    {
                        throw new ValidateException("TelnetPort", "The rcon port is needed!");
                    }
                    if (string.IsNullOrEmpty(server.ServerSystemdServiceName))
                    {
                        throw new ValidateException("ServerSystemdServiceName",
                                                    "The server service name is needed!");
                    }
                    if (string.IsNullOrEmpty(server.Name))
                    {
                        throw new ValidateException("Name", "The Gui name is needed!");
                    }
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.FieldName, e.Message);
                    return(await GoBackEditServer(server,
                                                  "Field is not set: " + e.Message));
                }

                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
                }

                try
                {
                    await _pavlovServerService.CreatePavlovServer(server);
                }
                catch (Exception e)
                {
                    return(await GoBackEditServer(server, e.Message, true));
                }
            }

            try
            {
                //save and validate server a last time
                resultServer = await _pavlovServerService.Upsert(server.toPavlovServer(server));
            }
            catch (ValidateException e)
            {
                ModelState.AddModelError(e.FieldName, e.Message);
                return(await GoBackEditServer(server,
                                              "Could not validate server -> " + e.Message, server.create));
            }

            if (ModelState.ErrorCount > 0)
            {
                return(await EditServer(server));
            }
            if (server.create)
            {
                return(Redirect("/PavlovServer/EditServerSelectedMaps/" + resultServer.Id));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
        /// <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);
        }
예제 #10
0
        public async Task <IActionResult> CreateServer(string apiKey, int sshServerId, bool shack, string email)
        {
            if (!HasAccess(apiKey))
            {
                return(BadRequest("No AuthKey set or wrong auth key!"));
            }
            var sshServer = await _sshServerSerivce.FindOne(sshServerId);

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

            var guid  = Guid.NewGuid().ToString();
            var model = new PavlovServerViewModel
            {
                Name                     = "Autogenerated: " + guid,
                TelnetPort               = sshServer.PavlovServers.Max(x => x.TelnetPort) + 1,
                DeletAfter               = 7,
                TelnetPassword           = Guid.NewGuid().ToString(),
                ServerPort               = sshServer.PavlovServers.Max(x => x.ServerPort) + 1,
                ServerFolderPath         = GeneratedServerPath + guid + "/",
                ServerSystemdServiceName = "pavlov" + guid.Replace("-", ""),
                ServerType               = ServerType.Community,
                ServerServiceState       = ServerServiceState.disabled,
                SshServer                = sshServer,
                AutoBalance              = false,
                SaveStats                = true,
                Shack                    = shack,
                sshServerId              = sshServer.Id,
                create                   = true,
                SshUsernameRoot          = sshServer.SshUsernameRootForHosting,
                SshPasswordRoot          = sshServer.SshPasswordRootForHosting,
                SshKeyFileNameRoot       = sshServer.SshKeyFileNameRootForHosting,
                SshPassphraseRoot        = sshServer.SshPassphraseRootForHosting
            };

            var user = await _userService.GetUserByEmail(email);

            if (user != null)
            {
                model.LiteDbUserId = user.Id.ToString();
                model.Owner        = user;
                if (!await _userManager.IsInRoleAsync(user, "ServerRent"))
                {
                    await _userManager.AddToRoleAsync(user, "ServerRent");
                }
            }

            try
            {
                await _pavlovServerService.CreatePavlovServer(model);
            }
            catch (Exception e)
            {
                await _sshServerSerivce.RemovePavlovServerFromDisk(model, true);

                DataBaseLogger.LogToDatabaseAndResultPlusNotify("Could not create rented server! " + model.Name, LogEventLevel.Fatal, _notifyService);
                return(BadRequest(e.Message));
            }


            var resultServer = await _pavlovServerService.Upsert(model.toPavlovServer(model));

            if (user == null)
            {
                await _reservedServersService.Add(new ReservedServer()
                {
                    Email = email, ServerId = resultServer.Id
                });
            }
            return(Ok(resultServer.Id));
        }