Ejemplo n.º 1
0
        public async Task <ActionResult> Restore(int id, int backupId = 0)
        {
            this.EnforceFeaturePermission("FileManager");
            if (backupId == 0)
            {
                return(this.SendError("No backup selected to restore."));
            }

            var service           = Service.GetSelectedService();
            var server            = TCAdmin.SDK.Objects.Server.GetSelectedServer();
            var directorySecurity = service.GetDirectorySecurityForCurrentUser();
            var fileSystem        = TCAdmin.SDK.Objects.Server.GetSelectedServer().FileSystemService;
            var backup            = new Backup(backupId);
            var backupSolution    = backup.Provider.Create <BackupSolution>();

            try
            {
                var randomFileName = TCAdmin.SDK.Misc.Random.RandomString(8, true, true) + ".zip";
                var saveTo         = FileSystem.CombinePath(server.OperatingSystem, service.RootDirectory, backup.Path, randomFileName);

                if (backupSolution.AllowsDirectDownload)
                {
                    var downloadUrl = await backupSolution.DirectDownloadLink(backup);

                    fileSystem.DownloadFile(saveTo, downloadUrl);
                }
                else
                {
                    var bytes = await backupSolution.DownloadBytes(backup);

                    var memoryStream = new MemoryStream(bytes);
                    var byteBuffer   = new byte[1024 * 1024 * 2];
                    int bytesRead;
                    memoryStream.Position = 0;

                    if (fileSystem.FileExists(saveTo))
                    {
                        fileSystem.DeleteFile(saveTo);
                    }

                    while ((bytesRead = memoryStream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                    {
                        fileSystem.AppendFile(saveTo, byteBuffer.Take(bytesRead).ToArray());
                    }

                    fileSystem.SetOwnerAutomatically(saveTo);
                }

                fileSystem.Extract(saveTo,
                                   FileSystem.CombinePath(server.OperatingSystem, service.RootDirectory, backup.Path),
                                   ObjectXml.ObjectToXml(directorySecurity));
                fileSystem.DeleteFile(saveTo);

                return(this.SendSuccess($"Restored <strong>{backup.Name}</strong>"));
            }
            catch (Exception e)
            {
                return(this.SendException(e, "Unable to restore backup - " + e.Message));
            }
        }
Ejemplo n.º 2
0
        public ActionResult Index()
        {
            var model = new MaintenanceModel {
                Service = new Service(Service.GetSelectedService().ServiceId), ServiceId = Service.GetSelectedService().ServiceId
            };

            return(View("Maintenance", model));
        }
Ejemplo n.º 3
0
        public ActionResult Index(int id)
        {
            var service = Service.GetSelectedService();
            var model   = new BackupManagerIndexModel
            {
                ServiceId = service.ServiceId,
                UsedQuota = GetBackupsQuotaUsed(service),
                MaxQuota  = GetBackupsQuota(service)
            };

            return(View(model));
        }
Ejemplo n.º 4
0
        public ActionResult List(int id, BackupType backupType)
        {
            this.EnforceFeaturePermission("FileManager");
            var service = Service.GetSelectedService();

            var backups = Backup.GetBackupsForService(service, backupType).ToList();

            return(Json(backups.Select(x => new
            {
                name = x.FileName,
                value = x.BackupId
            }), JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> Capacity(int id, BackupType backupType)
        {
            this.EnforceFeaturePermission("FileManager");
            var user    = TCAdmin.SDK.Session.GetCurrentUser();
            var service = Service.GetSelectedService();
            var value   = GetBackupsSize(service, backupType);
            var limit   = GetBackupsLimit(service, backupType);

            if (limit == -1)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            return(Json(new
            {
                limit,
                value
            }, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 6
0
        public ActionResult SetToken(int id, string token)
        {
            try
            {
                ObjectBase.GlobalSkipSecurityCheck = true;
                var service = Service.GetSelectedService();
                service.Variables["GSLT"] = token;
                service.Save();
                service.Configure();

                return(Json(new
                {
                    Message = "Successfully saved GSLT."
                }));
            }
            finally
            {
                ObjectBase.GlobalSkipSecurityCheck = false;
            }
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> Backup(int id, BackupRequest backupRequest)
        {
            this.EnforceFeaturePermission("FileManager");
            var service = Service.GetSelectedService();

            if (!backupRequest.Directories.Any() && !backupRequest.Files.Any())
            {
                return(this.SendError("Please choose at least <strong>1</strong> file or directory to backup."));
            }

            try
            {
                var backup = await Models.Objects.Backup.CreateAsync(service, backupRequest);

                backup.Save();
                return(this.SendSuccess($"Backed up <strong>{backupRequest.Name}</strong>"));
            }
            catch (Exception e)
            {
                return(this.SendException(e, "Failed to backup: " + e.Message));
            }
        }
Ejemplo n.º 8
0
        public static List <BackupType> AccessibleSolutions(int id)
        {
            var settings            = GlobalBackupSettings.Get();
            var accessibleSolutions = new List <BackupType>();
            var user    = TCAdmin.SDK.Session.GetCurrentUser();
            var service = Service.GetSelectedService();

            var s3Limit = service.Variables["S3:LIMIT"] != null
                ? long.Parse(service.Variables["S3:LIMIT"].ToString())
                : settings.DefaultS3Capacity;

            if (FileServer.GetFileServers().S3FileServers().Any() && s3Limit > 0 && settings.S3Enabled)
            {
                accessibleSolutions.Add(BackupType.S3);
            }

            var ftpLimit = service.Variables["Ftp:LIMIT"] != null
                ? long.Parse(service.Variables["Ftp:LIMIT"].ToString())
                : settings.DefaultFtpCapacity;

            if (FileServer.GetFileServers().FtpFileServers().Any() && ftpLimit > 0 && settings.FtpEnabled)
            {
                accessibleSolutions.Add(BackupType.Ftp);
            }

            var localLimit = service.Variables["Local:LIMIT"] != null
                ? long.Parse(service.Variables["Local:LIMIT"].ToString())
                : settings.DefaultLocalCapacity;

            if (localLimit > 0 && settings.LocalEnabled)
            {
                accessibleSolutions.Add(BackupType.Local);
            }

            return(accessibleSolutions);
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> BackupFile(int id, string file, BackupType backupType = BackupType.S3)
        {
            var service = Service.GetSelectedService();
            var server  = TCAdmin.GameHosting.SDK.Objects.Server.GetSelectedServer();
            var dirsec  = service.GetDirectorySecurityForCurrentUser();
            var vdir    = new TCAdmin.SDK.VirtualFileSystem.VirtualDirectory(server.OperatingSystem, dirsec);

            this.EnforceFeaturePermission("FileManager");
            if (string.IsNullOrEmpty(file))
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "Please choose a file to backup."
                }, HttpStatusCode.BadRequest));
            }

            var realFileName = Path.GetFileName(file);

            if (realFileName.Any(Path.GetInvalidFileNameChars().Contains) ||
                !Regex.IsMatch(realFileName, @"^[\w\-.@ ]+$"))
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "File contains invalid characters."
                }, HttpStatusCode.BadRequest));
            }

            var fileSystem     = server.FileSystemService;
            var backupSolution = Backup.ParseBackupSolution(backupType, service);
            var filePath       = vdir.CombineWithPhysicalPath(file);
            var fileSize       = fileSystem.GetFileSize(filePath);

            if (GetBackupsSize(service, backupType) + fileSize > GetBackupsLimit(service, backupType))
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "Backing up this file will exceed your assigned capacity."
                }, HttpStatusCode.BadRequest));
            }

            if (Backup.DoesBackupExist(service, realFileName, backupType))
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = $"Backup already exists with name <strong>{realFileName}</strong>"
                }, HttpStatusCode.BadRequest));
            }

            var remoteDownload = new RemoteDownload(server)
            {
                DirectorySecurity = service.GetDirectorySecurityForCurrentUser(),
                FileName          = filePath
            };

            var backupName = $"{realFileName}";
            var contents   = GetFileContents(remoteDownload.GetDownloadUrl());

            try
            {
                await backupSolution.Backup(backupName, contents, MimeMapping.GetMimeMapping(realFileName));

                var fileServer = FileServerModel.DetermineFileServer(service, backupType);
                var backup     = new Backup
                {
                    ServiceId    = service.ServiceId,
                    FileServerId = fileServer.FileServerId,
                    FileName     = backupName,
                    BackupType   = backupType,
                };
                backup.CustomFields["SIZE"] = fileSize;
                backup.GenerateKey();
                backup.Save();
            }
            catch (Exception e)
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "Failed to backup - " + e.Message + " | " + e.StackTrace
                }, HttpStatusCode.InternalServerError));
            }

            return(Json(new
            {
                Message = $"Backed up <strong>{backupName}</strong>"
            }));
        }
Ejemplo n.º 10
0
        public async Task <ActionResult> Restore(int id, string target, int backupId = 0)
        {
            this.EnforceFeaturePermission("FileManager");
            if (backupId == 0)
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "No backup selected to restore."
                }, HttpStatusCode.InternalServerError));
            }

            var service        = Service.GetSelectedService();
            var server         = TCAdmin.GameHosting.SDK.Objects.Server.GetSelectedServer();
            var dirsec         = service.GetDirectorySecurityForCurrentUser();
            var vdir           = new TCAdmin.SDK.VirtualFileSystem.VirtualDirectory(server.OperatingSystem, dirsec);
            var fileSystem     = TCAdmin.SDK.Objects.Server.GetSelectedServer().FileSystemService;
            var backup         = new Backup(backupId);
            var backupSolution = backup.BackupSolution;

            try
            {
                var targetpath = vdir.CombineWithPhysicalPath(target);
                var saveTo     = TCAdmin.SDK.Misc.FileSystem.CombinePath(targetpath, backup.FileName, server.OperatingSystem);

                if (backupSolution.AllowsDirectDownload)
                {
                    var downloadUrl = await backupSolution.DirectDownloadLink(backup.FileName);

                    fileSystem.DownloadFile(saveTo, downloadUrl);
                }
                else
                {
                    var bytes = await backupSolution.DownloadBytes(backup.FileName);

                    var memoryStream = new MemoryStream(bytes);
                    var byteBuffer   = new byte[1024 * 1024 * 2];
                    int bytesread;
                    memoryStream.Position = 0;

                    if (fileSystem.FileExists(saveTo))
                    {
                        fileSystem.DeleteFile(saveTo);
                    }

                    while ((bytesread = memoryStream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                    {
                        fileSystem.AppendFile(saveTo, byteBuffer.Take(bytesread).ToArray());
                    }
                    fileSystem.SetOwnerAutomatically(saveTo);
                }

                return(new JsonHttpStatusResult(new
                {
                    Message = $"Restored <strong>{backup.FileName}</strong>"
                }, HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                return(new JsonHttpStatusResult(new
                {
                    Message = "An error occurred: " + e.Message + " | " + e.StackTrace
                }, HttpStatusCode.InternalServerError));
            }
        }
Ejemplo n.º 11
0
        public static FileServer DetermineFileServer(Service service, BackupType backupType)
        {
            var        s3FileServerIds  = new List <int>();
            var        ftpFileServerIds = new List <int>();
            Server     server;
            Datacenter datacenter;

            if (TCAdmin.SDK.Utility.IsWebEnvironment())
            {
                service    = Service.GetSelectedService();
                server     = Server.GetSelectedServer();
                datacenter = Datacenter.GetSelectedDatacenter();
            }
            else
            {
                server     = new Server(service.ServerId);
                datacenter = new Datacenter(server.DatacenterId);
            }

            if (service.Variables["BACKUP:FILESERVERMODEL"] != null)
            {
                var model = JsonConvert.DeserializeObject <FileServerModel>(service.Variables["BACKUP:FILESERVERMODEL"]
                                                                            .ToString());

                s3FileServerIds.Add(model.S3FileServerId);
                ftpFileServerIds.Add(model.FtpFileServerId);
            }
            else if (!string.IsNullOrEmpty(server.CustomField15))
            {
                var model = JsonConvert.DeserializeObject <FileServerModel>(server.CustomField15);

                s3FileServerIds.Add(model.S3FileServerId);
                ftpFileServerIds.Add(model.FtpFileServerId);
            }
            else if (!string.IsNullOrEmpty(datacenter.CustomField15))
            {
                var model = JsonConvert.DeserializeObject <FileServerModel>(datacenter.CustomField15);

                s3FileServerIds.Add(model.S3FileServerId);
                ftpFileServerIds.Add(model.FtpFileServerId);
            }

            // Add absolutely last default servers.
            s3FileServerIds.AddRange(FileServer.GetFileServers().S3FileServers()
                                     .Select(s3FileServer => s3FileServer.FileServerId));

            ftpFileServerIds.AddRange(FileServer.GetFileServers().FtpFileServers()
                                      .Select(s3FileServer => s3FileServer.FileServerId));

            switch (backupType)
            {
            case BackupType.S3:
                var s3ValidFileServerId = s3FileServerIds.FirstOrDefault(x => x != -1);
                return(new FileServer(s3ValidFileServerId));

            case BackupType.Ftp:
                var ftpValidFileServerId = ftpFileServerIds.FirstOrDefault(x => x != -1);
                return(new FileServer(ftpValidFileServerId));

            case BackupType.Local:
                var customFileServer = new FileServer();
                customFileServer.FileServerId = -10;
                return(customFileServer);
            }

            return(FileServer.GetSelectedFileServer());
        }