Beispiel #1
0
        private void DownloadRemotelyFile(string remotelyUrl, string fileName)
        {
            var destinationDir = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "software_uploads", "99999999-9999-9999-9999-999999999999");

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    var directory = new DirectoryInfo(destinationDir);

                    try
                    {
                        if (!directory.Exists)
                        {
                            directory.Create();
                        }

                        using (var webClient = new WebClient())
                        {
                            webClient.DownloadFile(new Uri(remotelyUrl + "/Downloads/" + fileName), Path.Combine(destinationDir, fileName));
                        }
                    }
                    catch (Exception ex)
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }
Beispiel #2
0
        public bool Sync()
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    RoboCommand backup = new RoboCommand();
                    // events
                    backup.OnFileProcessed    += backup_OnFileProcessed;
                    backup.OnCommandCompleted += backup_OnCommandCompleted;
                    // copy options
                    backup.CopyOptions.Source             = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);
                    backup.CopyOptions.Destination        = ConfigurationManager.AppSettings["LocalStoragePath"].Trim('\\');
                    backup.CopyOptions.CopySubdirectories = true;
                    backup.CopyOptions.UseUnbufferedIo    = true;
                    // select options
                    //backup.SelectionOptions.OnlyCopyArchiveFilesAndResetArchiveFlag = true;
                    backup.CopyOptions.Mirror            = true;
                    backup.CopyOptions.Purge             = false;
                    backup.SelectionOptions.ExcludeOlder = true;
                    backup.LoggingOptions.VerboseOutput  = true;
                    // retry options
                    backup.RetryOptions.RetryCount    = 1;
                    backup.RetryOptions.RetryWaitTime = 2;
                    backup.Start();
                    return(true);
                }
                return(false);
            }
        }
        public bool DeleteImageFolders(string imageName)
        {
            //Check again
            if (string.IsNullOrEmpty(imageName))
            {
                return(false);
            }

            var primaryDp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (primaryDp.Location == "Local")
            {
                try
                {
                    Directory.Delete(primaryDp.PhysicalPath + "images" + Path.DirectorySeparatorChar + imageName,
                                     true);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    return(false);
                }
            }
            else if (primaryDp.Location == "Remote")
            {
                using (var unc = new UncServices())
                {
                    var basePath    = @"\\" + primaryDp.Server + @"\" + primaryDp.ShareName;
                    var smbPassword = new EncryptionServices().DecryptText(primaryDp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, primaryDp.RwUsername, primaryDp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        try
                        {
                            Directory.Delete(basePath + @"\images" + @"\" +
                                             imageName, true);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message);
                            return(false);
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                        return(false);
                    }
                }
            }
            else
            {
                log.Error("Could Not Determine Primary Distribution Point Location Type");
                return(false);
            }

            return(true);
        }
        public List <FileInfo> GetMunkiResources(string type)
        {
            FileInfo[] directoryFiles = null;
            var        pkgInfoFiles   = SettingServices.GetSettingValue(SettingStrings.MunkiBasePath) +
                                        Path.DirectorySeparatorChar + type + Path.DirectorySeparatorChar;

            if (SettingServices.GetSettingValue(SettingStrings.MunkiPathType) == "Local")
            {
                var di = new DirectoryInfo(pkgInfoFiles);

                try
                {
                    directoryFiles = di.GetFiles("*.*");
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            }

            else
            {
                using (var unc = new UncServices())
                {
                    var smbPassword =
                        new EncryptionServices().DecryptText(
                            SettingServices.GetSettingValue(SettingStrings.MunkiSMBPassword));
                    var smbDomain = string.IsNullOrEmpty(SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain))
                        ? ""
                        : SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain);
                    if (
                        unc.NetUseWithCredentials(SettingServices.GetSettingValue(SettingStrings.MunkiBasePath),
                                                  SettingServices.GetSettingValue(SettingStrings.MunkiSMBUsername), smbDomain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        var di = new DirectoryInfo(pkgInfoFiles);
                        try
                        {
                            directoryFiles = di.GetFiles("*.*");
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message);
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " +
                                  SettingServices.GetSettingValue(SettingStrings.MunkiBasePath) + "\r\nLastError = " +
                                  unc.LastError);
                    }
                }
            }

            return(directoryFiles.ToList());
        }
Beispiel #5
0
        public bool Sync()
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var folder in new [] { "client_versions", "software_uploads" })
                    {
                        RoboCommand backup = new RoboCommand();
                        // events
                        backup.OnError += Backup_OnError;

                        // copy options
                        backup.CopyOptions.Source             = ServiceSetting.GetSettingValue(SettingStrings.StoragePath) + folder;
                        backup.CopyOptions.Destination        = thisComServer.LocalStoragePath + folder.Trim('\\');
                        backup.CopyOptions.CopySubdirectories = true;
                        backup.CopyOptions.UseUnbufferedIo    = true;
                        if (thisComServer.ReplicationRateIpg != 0)
                        {
                            backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                        }
                        else
                        {
                            backup.CopyOptions.InterPacketGap = 0;
                        }
                        // select options
                        backup.CopyOptions.Mirror = true;
                        backup.CopyOptions.Purge  = true;

                        backup.LoggingOptions.VerboseOutput = false;
                        // retry options
                        backup.RetryOptions.RetryCount    = 3;
                        backup.RetryOptions.RetryWaitTime = 10;
                        backup.Start().Wait();
                    }
                    return(true);
                }
                return(false);
            }
        }
Beispiel #6
0
        public string GetHdFileSize(string imageName, string hd)
        {
            var primaryDp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (primaryDp == null)
            {
                return("No Primary Dp");
            }
            if (primaryDp.Location == "Local")
            {
                try
                {
                    var imagePath = primaryDp.PhysicalPath + "images" + Path.DirectorySeparatorChar + imageName +
                                    Path.DirectorySeparatorChar + "hd" + hd;
                    var size = new FileOpsServices().GetDirectorySize(new DirectoryInfo(imagePath)) / 1024f / 1024f / 1024f;
                    return(Math.Abs(size) < 0.1f ? "< 100M" : size.ToString("#.##") + " GB");
                }
                catch
                {
                    return("N/A");
                }
            }
            if (primaryDp.Location == "Remote")
            {
                using (var unc = new UncServices())
                {
                    var basePath    = @"\\" + primaryDp.Server + @"\" + primaryDp.ShareName;
                    var smbPassword = new EncryptionServices().DecryptText(primaryDp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, primaryDp.RwUsername, primaryDp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        try
                        {
                            var imagePath = basePath + @"\images\" + imageName + @"\hd" + hd;
                            var size      = new FileOpsServices().GetDirectorySize(new DirectoryInfo(imagePath)) / 1024f / 1024f /
                                            1024f;
                            return(Math.Abs(size) < 0.1f ? "< 100M" : size.ToString("#.##") + " GB");
                        }
                        catch
                        {
                            return("N/A");
                        }
                    }
                    log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                    return("N/A");
                }
            }
            log.Error("Could Not Determine Primary Distribution Point Location Type");
            return("N/A");
        }
Beispiel #7
0
        public DtoActionResult Delete(int id)
        {
            var u = Get(id);

            if (u == null)
            {
                return new DtoActionResult {
                           ErrorMessage = "Attachment Not Found", Id = 0
                }
            }
            ;

            _uow.AttachmentRepository.Delete(id);
            _uow.Save();

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(u.DirectoryGuid) || string.IsNullOrEmpty(u.Name) || u.DirectoryGuid == Path.DirectorySeparatorChar.ToString() || u.Name == Path.DirectorySeparatorChar.ToString())
                        {
                            //ignored
                        }
                        else
                        {
                            var storagePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);
                            File.Delete(Path.Combine(storagePath, "attachments", u.DirectoryGuid, u.Name));
                            var dirFiles = Directory.GetFiles(Path.Combine(storagePath, "attachments", u.DirectoryGuid));
                            if (dirFiles.Length == 0)
                            {
                                Directory.Delete(Path.Combine(storagePath, "attachments", u.DirectoryGuid));
                            }
                        }
                    }
                    catch
                    {
                        //ignored
                    }
                }
            }

            var actionResult = new DtoActionResult();

            actionResult.Success = true;
            actionResult.Id      = u.Id;
            return(actionResult);
        }
    }
Beispiel #8
0
        public void ChunkingComplete()
        {
            var fileName = Request["qqfilename"];

            if (string.IsNullOrEmpty(fileName) || fileName == Path.DirectorySeparatorChar.ToString())
            {
                throw new HttpException();
            }
            var moduleGuid = Request["moduleGuid"];

            if (string.IsNullOrEmpty(moduleGuid))
            {
                throw new HttpException();
            }
            var fullPath = Path.Combine(_basePath, "software_uploads", moduleGuid, fileName);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    var uploadedFile = new EntityUploadedFile();
                    uploadedFile.Name = fileName;
                    uploadedFile.Guid = moduleGuid;
                    uploadedFile.Hash = Utility.GetFileHash(fullPath);

                    var result = new ServiceUploadedFile().AddFile(uploadedFile);
                    if (!result.Success)
                    {
                        try
                        {
                            File.Delete(fullPath);
                        }
                        catch
                        {
                            //ignored
                        }
                        throw new HttpException();
                    }
                }
                else
                {
                    throw new HttpException("Could Not Reach Storage Path");
                }
            }
        }
        public HttpResponseMessage GetAttachment(int id)
        {
            var attachment = new ServiceAttachment().Get(id);

            if (attachment == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    var fullPath = Path.Combine(basePath, "attachments", attachment.DirectoryGuid, attachment.Name);
                    if (File.Exists(fullPath))
                    {
                        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                        try
                        {
                            var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
                            result.Content = new StreamContent(stream);

                            result.Content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                            result.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                            result.Content.Headers.ContentDisposition.FileName = attachment.Name;
                            return(result);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.Message);
                        }
                    }
                }
                else
                {
                    throw new HttpException("Could Not Reach Storage Path");
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
Beispiel #10
0
        public bool CopyMsiToClientUpdate()
        {
            foreach (var type in new List <bool> {
                true, false
            })
            {
                var msi      = new ServiceMsiUpdater().UpdateMsis(is64bit: type);
                var fileName = new ServiceMsiUpdater().GetNameForExport(is64bit: type);

                var destinationDir = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "client_versions");

                using (var unc = new UncServices())
                {
                    if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                    {
                        var directory = new DirectoryInfo(destinationDir);
                        try
                        {
                            if (!directory.Exists)
                            {
                                directory.Create();
                            }

                            File.WriteAllBytes(Path.Combine(destinationDir, fileName), msi);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.Message);
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }


            return(true);
        }
Beispiel #11
0
        public List <ImageFileInfo> GetPartitionFileSize(string imageName, string hd, string partition)
        {
            var primaryDp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (primaryDp == null)
            {
                return(null);
            }
            var imageFileInfo = new ImageFileInfo();

            if (primaryDp.Location == "Local")
            {
                try
                {
                    var imageFile =
                        Directory.GetFiles(
                            primaryDp.PhysicalPath + "images" + Path.DirectorySeparatorChar + imageName +
                            Path.DirectorySeparatorChar + "hd" + hd +
                            Path.DirectorySeparatorChar,
                            "part" + partition + ".*").FirstOrDefault();

                    var fi = new FileInfo(imageFile);
                    imageFileInfo = new ImageFileInfo
                    {
                        FileName = fi.Name,
                        FileSize = (fi.Length / 1024f / 1024f).ToString("#.##") + " MB"
                    };
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    return(null);
                }
            }
            else if (primaryDp.Location == "Remote")
            {
                using (var unc = new UncServices())
                {
                    var basePath    = @"\\" + primaryDp.Server + @"\" + primaryDp.ShareName;
                    var smbPassword = new EncryptionServices().DecryptText(primaryDp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, primaryDp.RwUsername, primaryDp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        try
                        {
                            var imageFile =
                                Directory.GetFiles(basePath + @"\images\" + imageName +
                                                   @"\" + "hd" + hd + @"\", "part" + partition + ".*").FirstOrDefault();

                            var fi = new FileInfo(imageFile);
                            imageFileInfo = new ImageFileInfo
                            {
                                FileName = fi.Name,
                                FileSize = (fi.Length / 1024f / 1024f).ToString("#.##") + " MB"
                            };
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message);
                            return(null);
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                        return(null);
                    }
                }
            }
            else
            {
                log.Error("Could Not Determine Primary Distribution Point Location Type");
                return(null);
            }

            return(new List <ImageFileInfo> {
                imageFileInfo
            });
        }
Beispiel #12
0
        private bool FromCom()
        {
            var uow = new UnitOfWork();
            var imagesToReplicate = new List <EntityImage>();

            Logger.Info("Starting Image Replication From Com Servers");
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }
            if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True"))
            {
                Logger.Info("Image replication is not used when direct smb imaging is enabled.");
                return(true); //Don't need to sync images when direct to smb is used.
            }
            //find all images that need copied from com servers to the SMB share
            var completedImages = uow.ImageRepository.Get(x => !string.IsNullOrEmpty(x.LastUploadGuid));

            if (completedImages == null)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            if (completedImages.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //check if images already exist on smb share
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    if (!Directory.Exists(Path.Combine(basePath, "images")))
                    {
                        try
                        {
                            Directory.CreateDirectory(Path.Combine(basePath, "images"));
                        }
                        catch
                        {
                            Logger.Error("Could Not Sync Images.  The images folder could not be created on smb share");
                            return(false);
                        }
                    }
                    foreach (var image in completedImages)
                    {
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue; //should never happen, but could potential erase all images if so, when syncing
                        }
                        var imagePath = Path.Combine(basePath, "images", image.Name);
                        if (!Directory.Exists(imagePath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        var guidPath = Path.Combine(imagePath, "guid");
                        if (!File.Exists(guidPath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        using (StreamReader reader = new StreamReader(guidPath))
                        {
                            var fileGuid = reader.ReadLine() ?? "";
                            if (!fileGuid.Equals(image.LastUploadGuid))
                            {
                                //image on smb is older than what database says
                                imagesToReplicate.Add(image);
                                continue;
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (imagesToReplicate.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //find com servers with the image to replicate

            var comServers   = uow.ClientComServerRepository.Get(x => x.IsImagingServer);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            var comImageDict = new Dictionary <int, int>();

            foreach (var image in imagesToReplicate)
            {
                foreach (var com in comServers)
                {
                    var hasImage = new APICall().ClientComServerApi.CheckImageExists(com.Url, "", decryptedKey, image.Id);
                    if (hasImage)
                    {
                        if (!comImageDict.ContainsKey(image.Id))
                        {
                            comImageDict.Add(image.Id, com.Id);
                            break; //only add image to a single com server, don't want to replicate image multiple times if multiple coms have it
                        }
                    }
                }
            }

            var groupedByServer = comImageDict.GroupBy(x => x.Value).ToDictionary(y => y.Key, y => y.Select(x => x.Key).ToList());

            foreach (var c in groupedByServer)
            {
                var comServerId      = c.Key;
                var thisComImageList = new List <int>();
                foreach (var imageId in c.Value)
                {
                    thisComImageList.Add(imageId);
                }

                var comServer = new ServiceClientComServer().GetServer(comServerId);
                new APICall().ClientComServerApi.SyncComToSmb(comServer.Url, "", decryptedKey, thisComImageList);
            }
            return(true);
        }
Beispiel #13
0
        public List <DtoServerImageRepStatus> GetReplicationStatus(int imageId)
        {
            var list         = new List <DtoServerImageRepStatus>();
            var image        = GetImage(imageId);
            var comServers   = _uow.ClientComServerRepository.Get(x => x.IsImagingServer);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            foreach (var com in comServers)
            {
                var status = new DtoServerImageRepStatus();
                status.Servername = com.DisplayName;
                var hasImage = new APICall().ClientComServerApi.CheckImageExists(com.Url, "", decryptedKey, imageId);
                if (hasImage)
                {
                    status.Status = "Replicated";
                }
                else
                {
                    status.Status = "Not Replicated";
                }

                list.Add(status);
            }

            //check if images already exist on smb share
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    var imagePath = Path.Combine(basePath, "images", image.Name);

                    var guidPath = Path.Combine(imagePath, "guid");
                    if (File.Exists(guidPath))
                    {
                        using (StreamReader reader = new StreamReader(guidPath))
                        {
                            var fileGuid = reader.ReadLine() ?? "";
                            if (fileGuid.Equals(image.LastUploadGuid))
                            {
                                var status = new DtoServerImageRepStatus();
                                status.Servername = basePath.Replace(@"\", "\\");
                                status.Status     = "Replicated";
                                list.Add(status);
                            }
                            else
                            {
                                var status = new DtoServerImageRepStatus();
                                status.Servername = basePath.Replace(@"\", "\\");
                                status.Status     = "Not Replicated";
                                list.Add(status);
                            }
                        }
                    }
                    else
                    {
                        var status = new DtoServerImageRepStatus();
                        status.Servername = basePath.Replace(@"\", "\\");
                        status.Status     = "Not Replicated";
                        list.Add(status);
                    }
                }
            }

            return(list);
        }
Beispiel #14
0
        public DtoActionResult RunHealthCheck()
        {
            var comServer = _uow.ClientComServerRepository.Get(x => x.IsRemoteAccessServer).FirstOrDefault();

            if (comServer == null)
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = "No Active Remote Access Servers Were Found"
                });
            }

            //check connection to remotely api
            var status = new APICall().RemoteAccessApi.RemotelyStatus(comServer.RemoteAccessUrl);

            if (status == null)
            {
                return new DtoActionResult()
                       {
                           ErrorMessage = "Could Not Contact Remote Access API"
                       }
            }
            ;
            status = status.Replace("\"", "");
            status = status.Replace("\\", "");
            if (status != "true")
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = "Could Not Contact Remote Access API"
                });
            }

            //check api connection with auth header, should return false with fake device id
            var auth   = new EncryptionServices().DecryptText(comServer.RaAuthHeaderEncrypted);
            var online = new APICall().RemoteAccessApi.RemotelyIsDeviceOnline(comServer.RemoteAccessUrl, "abc", auth);

            if (online == null)
            {
                return new DtoActionResult()
                       {
                           ErrorMessage = "Remote Access API Unauthorized"
                       }
            }
            ;
            online = online.Replace("\"", "");
            online = online.Replace("\\", "");
            if (online != "false")
            {
                return new DtoActionResult()
                       {
                           ErrorMessage = "Remote Access API Unauthorized"
                       }
            }
            ;

            //verify files exist
            var basePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "software_uploads", "99999999-9999-9999-9999-999999999999");

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    try
                    {
                        var installer = Path.Combine(basePath, "Remotely_Installer.exe");
                        var x64       = Path.Combine(basePath, "Remotely-Win10-x64.zip");
                        var x86       = Path.Combine(basePath, "Remotely-Win10-x86.zip");

                        //no need to check if exists, exception will catch when looking for size
                        var hasSize = new FileInfo(installer).Length > 0;
                        if (!hasSize)
                        {
                            return new DtoActionResult()
                                   {
                                       ErrorMessage = "Remotely_Installer.exe Is Missing From Storage Path"
                                   }
                        }
                        ;
                        hasSize = new FileInfo(x64).Length > 0;
                        if (!hasSize)
                        {
                            return new DtoActionResult()
                                   {
                                       ErrorMessage = "Remotely x64 File Is Missing From Storage Path"
                                   }
                        }
                        ;
                        hasSize = new FileInfo(x86).Length > 0;
                        if (!hasSize)
                        {
                            return new DtoActionResult()
                                   {
                                       ErrorMessage = "Remotely x86 File Is Missing From Storage Path"
                                   }
                        }
                        ;
                    }
                    catch
                    {
                        return(new DtoActionResult()
                        {
                            ErrorMessage = "Remote Access Files Have Not Been Copied To The Storage Path"
                        });
                    }
                }
                else
                {
                    return(new DtoActionResult()
                    {
                        ErrorMessage = "Could Not Determine If Remote Access Installer Files Are Available"
                    });
                }
            }
            return(new DtoActionResult()
            {
                Success = true
            });
        }
    }
}
Beispiel #15
0
        private bool ToCom()
        {
            var uow = new UnitOfWork();
            var imagesToReplicate = new List <EntityImage>();

            Logger.Info("Starting Image Replication To Com Servers");
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                Logger.Info("Image replication is not used when storage type is set to local.");
                return(true);
            }
            if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True"))
            {
                Logger.Info("Image replication is not used when direct smb imaging is enabled.");
                return(true); //Don't need to sync images when direct to smb is used.
            }

            //find all images that need copied from SMB share to com servers
            var completedImages = uow.ImageRepository.Get(x => !string.IsNullOrEmpty(x.LastUploadGuid));

            if (completedImages == null)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            if (completedImages.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //check if images already exist on smb share
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var image in completedImages)
                    {
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue; //should never happen, but could potential erase all images if so, when syncing
                        }
                        var imagePath = Path.Combine(basePath, "images", image.Name);
                        if (!Directory.Exists(imagePath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        var guidPath = Path.Combine(imagePath, "guid");
                        if (!File.Exists(guidPath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        using (StreamReader reader = new StreamReader(guidPath))
                        {
                            var fileGuid = reader.ReadLine() ?? "";
                            if (fileGuid.Equals(image.LastUploadGuid))
                            {
                                //image on smb share matches what database says, this is the master and should be replicated to com servers
                                imagesToReplicate.Add(image);
                                continue;
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (imagesToReplicate.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //find com servers that need this image

            var comServers   = uow.ClientComServerRepository.Get(x => x.IsImagingServer);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            var comImageList = new List <DtoRepImageCom>();

            foreach (var com in comServers)
            {
                foreach (var image in imagesToReplicate)
                {
                    var hasImage = new APICall().ClientComServerApi.CheckImageExists(com.Url, "", decryptedKey, image.Id);
                    if (hasImage)
                    {
                        continue; //already has image move to next com server
                    }
                    else
                    {
                        var comImage = new DtoRepImageCom();
                        comImage.ComServerId = com.Id;
                        comImage.ImageId     = image.Id;
                        comImageList.Add(comImage);
                    }
                }
            }

            if (comImageList.Count == 0)
            {
                Logger.Info("Com Server Images Are All Up To Date.  Skipping Replication.");
                return(true);
            }

            foreach (var c in comImageList.GroupBy(x => x.ComServerId))
            {
                var comServerId      = c.First().ComServerId;
                var thisComImageList = new List <int>();
                foreach (var imageId in c)
                {
                    thisComImageList.Add(imageId.ImageId);
                }

                var comServer = new ServiceClientComServer().GetServer(comServerId);
                new APICall().ClientComServerApi.SyncSmbToCom(comServer.Url, "", decryptedKey, thisComImageList);
            }
            return(true);
        }
Beispiel #16
0
        public string GetLVMFileNameWithFullPath(string imageName, string schemaHdNumber, string vgName, string lvName,
                                                 string extension)
        {
            var primaryDp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (primaryDp == null)
            {
                return(string.Empty);
            }

            var filePath = "";

            if (primaryDp.Location == "Local")
            {
                var imagePath = primaryDp.PhysicalPath + "images" +
                                Path.DirectorySeparatorChar + imageName + Path.DirectorySeparatorChar + "hd" +
                                schemaHdNumber;
                try
                {
                    filePath =
                        Directory.GetFiles(
                            imagePath + Path.DirectorySeparatorChar,
                            vgName + "-" + lvName + "." + extension + ".*")
                        .FirstOrDefault();
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            }
            else if (primaryDp.Location == "Remote")
            {
                using (var unc = new UncServices())
                {
                    var basePath    = @"\\" + primaryDp.Server + @"\" + primaryDp.ShareName;
                    var smbPassword = new EncryptionServices().DecryptText(primaryDp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, primaryDp.RwUsername, primaryDp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        var imagePath = basePath + @"\images\" + imageName + @"\hd" +
                                        schemaHdNumber;
                        try
                        {
                            filePath =
                                Directory.GetFiles(
                                    imagePath + @"\",
                                    vgName + "-" + lvName + "." + extension + ".*")
                                .FirstOrDefault();
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message);
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                    }
                }
            }
            else
            {
                log.Error("Could Not Determine Primary Distribution Point Location Type");
            }

            return(filePath);
        }
Beispiel #17
0
        public string ReadSchemaFile(string imageName)
        {
            var primaryDp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (primaryDp == null)
            {
                return(string.Empty);
            }
            var schemaText = "";

            if (primaryDp.Location == "Local")
            {
                try
                {
                    var path = primaryDp.PhysicalPath + "images" + Path.DirectorySeparatorChar +
                               imageName + Path.DirectorySeparatorChar + "schema";

                    using (var reader = new StreamReader(path))
                    {
                        schemaText = reader.ReadLine() ?? "";
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Could Not Read Schema File On The Primary Distribution Point");
                    log.Error(ex.Message);
                }
            }
            else if (primaryDp.Location == "Remote")
            {
                using (var unc = new UncServices())
                {
                    var basePath    = @"\\" + primaryDp.Server + @"\" + primaryDp.ShareName;
                    var smbPassword = new EncryptionServices().DecryptText(primaryDp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, primaryDp.RwUsername, primaryDp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        try
                        {
                            var path = basePath + @"\images\" + imageName + @"\schema";

                            using (var reader = new StreamReader(path))
                            {
                                schemaText = reader.ReadLine() ?? "";
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("Could Not Read Schema File On The Primary Distribution Point");
                            log.Error(ex.Message);
                        }
                    }
                    else
                    {
                        log.Error("Could Not Read Schema File On The Primary Distribution Point");
                        log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                    }
                }
            }
            else
            {
                log.Error("Could Not Determine Primary Distribution Point Location Type");
            }

            return(schemaText);
        }
Beispiel #18
0
        public bool SyncToCom(List <int> imageIds)
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var imageId in imageIds)
                    {
                        var image = new ServiceImage().GetImage(imageId);
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue;
                        }
                        var sourcePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "images", image.Name);
                        var destPath   = Path.Combine(thisComServer.LocalStoragePath, "images", image.Name).TrimEnd('\\');

                        using (RoboCommand backup = new RoboCommand())
                        {
                            // events

                            /*backup.OnFileProcessed += backup_OnFileProcessed;
                             * backup.OnCommandCompleted += backup_OnCommandCompleted;
                             * backup.OnCopyProgressChanged += Backup_OnCopyProgressChanged;
                             */
                            backup.OnError += Backup_OnError;
                            // copy options
                            backup.CopyOptions.Source             = sourcePath;
                            backup.CopyOptions.Destination        = destPath;
                            backup.CopyOptions.CopySubdirectories = true;
                            backup.SelectionOptions.IncludeSame   = true;
                            backup.CopyOptions.UseUnbufferedIo    = true;
                            if (thisComServer.ReplicationRateIpg != 0)
                            {
                                backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                            }
                            else
                            {
                                backup.CopyOptions.InterPacketGap = 0;
                            }
                            // select options
                            backup.CopyOptions.Mirror           = true;
                            backup.CopyOptions.Purge            = true;
                            backup.LoggingOptions.VerboseOutput = false;

                            backup.SelectionOptions.ExcludeFiles = "guid";
                            // retry options
                            backup.RetryOptions.RetryCount    = 3;
                            backup.RetryOptions.RetryWaitTime = 60;

                            backup.Start().Wait();
                            if (backup.Results.Status.ExitCodeValue == 0 || backup.Results.Status.ExitCodeValue == 1)
                            {
                                //backup succesful, copy the guid now
                                try
                                {
                                    var guidPath = Path.Combine(sourcePath, "guid");
                                    File.Copy(guidPath, destPath + Path.DirectorySeparatorChar + "guid");
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex.Message);
                                    Logger.Error("Could Not Replicate Image " + image.Name);
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #19
0
        public int Apply(int templateId)
        {
            var errorCount = 0;
            var basePath   = SettingServices.GetSettingValue(SettingStrings.MunkiBasePath) + Path.DirectorySeparatorChar +
                             "manifests" +
                             Path.DirectorySeparatorChar;

            var groups = _groupMunkiServices.GetGroupsForManifestTemplate(templateId);

            if (SettingServices.GetSettingValue(SettingStrings.MunkiPathType) == "Local")
            {
                foreach (var munkiGroup in groups)
                {
                    var effectiveManifest = new EffectiveMunkiTemplate().Group(munkiGroup.GroupId);
                    var computersInGroup  = _groupServices.GetGroupMembersWithImages(munkiGroup.GroupId);
                    foreach (var computer in computersInGroup)
                    {
                        if (!WritePath(basePath + computer.Name, Encoding.UTF8.GetString(effectiveManifest.ToArray())))
                        {
                            errorCount++;
                        }
                    }
                }
            }
            else
            {
                using (var unc = new UncServices())
                {
                    var smbPassword =
                        new EncryptionServices().DecryptText(
                            SettingServices.GetSettingValue(SettingStrings.MunkiSMBPassword));
                    var smbDomain = string.IsNullOrEmpty(SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain))
                        ? ""
                        : SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain);
                    if (
                        unc.NetUseWithCredentials(SettingServices.GetSettingValue(SettingStrings.MunkiBasePath),
                                                  SettingServices.GetSettingValue(SettingStrings.MunkiSMBUsername), smbDomain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        foreach (var munkiGroup in groups)
                        {
                            var effectiveManifest = new EffectiveMunkiTemplate().Group(munkiGroup.GroupId);
                            var computersInGroup  = _groupServices.GetGroupMembersWithImages(munkiGroup.GroupId);
                            foreach (var computer in computersInGroup)
                            {
                                if (
                                    !WritePath(basePath + computer.Name,
                                               Encoding.UTF8.GetString(effectiveManifest.ToArray())))
                                {
                                    errorCount++;
                                }
                            }
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " +
                                  SettingServices.GetSettingValue(SettingStrings.MunkiBasePath) + "\r\nLastError = " +
                                  unc.LastError);
                        foreach (var munkiGroup in groups)
                        {
                            var computersInGroup = _groupServices.GetGroupMembersWithImages(munkiGroup.GroupId);
                            errorCount += computersInGroup.Count();
                        }
                    }
                }
            }
            var computers = _computerMunkiServices.GetComputersForManifestTemplate(templateId);

            if (SettingServices.GetSettingValue(SettingStrings.MunkiPathType) == "Local")
            {
                foreach (var munkiComputer in computers)
                {
                    var effectiveManifest = new EffectiveMunkiTemplate().Computer(munkiComputer.ComputerId);
                    var computer          = _computerServices.GetComputer(munkiComputer.ComputerId);
                    if (!WritePath(basePath + computer.Name, Encoding.UTF8.GetString(effectiveManifest.ToArray())))
                    {
                        errorCount++;
                    }
                }
            }
            else
            {
                using (var unc = new UncServices())
                {
                    var smbPassword =
                        new EncryptionServices().DecryptText(
                            SettingServices.GetSettingValue(SettingStrings.MunkiSMBPassword));
                    var smbDomain = string.IsNullOrEmpty(SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain))
                        ? ""
                        : SettingServices.GetSettingValue(SettingStrings.MunkiSMBDomain);
                    if (
                        unc.NetUseWithCredentials(SettingServices.GetSettingValue(SettingStrings.MunkiBasePath),
                                                  SettingServices.GetSettingValue(SettingStrings.MunkiSMBUsername), smbDomain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        foreach (var munkiComputer in computers)
                        {
                            var effectiveManifest =
                                new EffectiveMunkiTemplate().Computer(munkiComputer.ComputerId);
                            var computer = _computerServices.GetComputer(munkiComputer.ComputerId);

                            if (
                                !WritePath(basePath + computer.Name,
                                           Encoding.UTF8.GetString(effectiveManifest.ToArray())))
                            {
                                errorCount++;
                            }
                        }
                    }
                    else
                    {
                        log.Error("Failed to connect to " +
                                  SettingServices.GetSettingValue(SettingStrings.MunkiBasePath) + "\r\nLastError = " +
                                  unc.LastError);
                        errorCount += computers.Count();
                    }
                }
            }

            if (errorCount > 0)
            {
                return(errorCount);
            }

            var includedTemplates = new List <MunkiManifestTemplateEntity>();

            foreach (var munkiGroup in groups)
            {
                foreach (var template in _groupServices.GetGroupMunkiTemplates(munkiGroup.GroupId))
                {
                    includedTemplates.Add(_munkiManifestTemplateServices.GetManifest(template.MunkiTemplateId));
                }
            }

            foreach (var computer in computers)
            {
                foreach (var template in _computerServices.GetMunkiTemplates(computer.ComputerId))
                {
                    includedTemplates.Add(_munkiManifestTemplateServices.GetManifest(template.MunkiTemplateId));
                }
            }

            foreach (var template in includedTemplates)
            {
                template.ChangesApplied = 1;
                _munkiManifestTemplateServices.UpdateManifest(template);
            }

            return(0);
        }
Beispiel #20
0
        public DpFreeSpaceDTO GetDpFreeSpace()
        {
            var dp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (dp == null)
            {
                return(new DpFreeSpaceDTO());
            }

            var dpFreeSpace = new DpFreeSpaceDTO();

            if (dp.Location == "Remote")
            {
                var basePath = @"\\" + dp.Server + @"\" + dp.ShareName;
                dpFreeSpace.dPPath = basePath;
                using (var unc = new UncServices())
                {
                    var smbPassword = new EncryptionServices().DecryptText(dp.RwPassword);
                    if (
                        unc.NetUseWithCredentials(basePath, dp.RwUsername, dp.Domain,
                                                  smbPassword) || unc.LastError == 1219)
                    {
                        ulong freespace = 0;
                        ulong total     = 0;
                        var   success   = DriveFreeBytes(basePath, out freespace, out total);

                        if (!success)
                        {
                            return(null);
                        }

                        var freePercent = 0;
                        var usedPercent = 0;

                        if (total > 0 && freespace > 0)
                        {
                            freePercent = (int)(0.5f + 100f * Convert.ToInt64(freespace) / Convert.ToInt64(total));
                            usedPercent =
                                (int)(0.5f + 100f * Convert.ToInt64(total - freespace) / Convert.ToInt64(total));
                        }
                        dpFreeSpace.freespace   = freespace;
                        dpFreeSpace.total       = total;
                        dpFreeSpace.freePercent = freePercent;
                        dpFreeSpace.usedPercent = usedPercent;
                    }
                    else
                    {
                        log.Error("Failed to connect to " + basePath + "\r\nLastError = " + unc.LastError);
                    }
                }
            }
            else
            {
                dpFreeSpace.dPPath = dp.PhysicalPath;

                if (Directory.Exists(dp.PhysicalPath))
                {
                    ulong freespace = 0;
                    ulong total     = 0;

                    var  isUnix = Environment.OSVersion.ToString().Contains("Unix");
                    bool success;
                    if (isUnix)
                    {
                        success = MonoDriveFreeBytes(dp.PhysicalPath, out freespace, out total);
                    }
                    else
                    {
                        success = DriveFreeBytes(dp.PhysicalPath, out freespace, out total);
                    }


                    if (!success)
                    {
                        return(null);
                    }

                    var freePercent = 0;
                    var usedPercent = 0;

                    if (total > 0 && freespace > 0)
                    {
                        freePercent = (int)(0.5f + 100f * Convert.ToInt64(freespace) / Convert.ToInt64(total));
                        usedPercent =
                            (int)(0.5f + 100f * Convert.ToInt64(total - freespace) / Convert.ToInt64(total));
                    }
                    dpFreeSpace.freespace   = freespace;
                    dpFreeSpace.total       = total;
                    dpFreeSpace.freePercent = freePercent;
                    dpFreeSpace.usedPercent = usedPercent;
                }
            }

            return(dpFreeSpace);
        }
Beispiel #21
0
        private string VerifySoftware(EntityPolicyModules policyModule)
        {
            var softwareModule = new ServiceSoftwareModule().GetModule(policyModule.ModuleId);

            if (string.IsNullOrEmpty(softwareModule.Name))
            {
                return("A Software Module Has An Invalid Name");
            }

            if (softwareModule.Archived)
            {
                return("Software Module: " + softwareModule.Name + " Is Archived");
            }

            if (string.IsNullOrEmpty(softwareModule.Guid))
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid GUID");
            }

            int value;

            if (!int.TryParse(softwareModule.Timeout.ToString(), out value))
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid Timeout");
            }

            if (string.IsNullOrEmpty(softwareModule.Command))
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid Command");
            }

            if (!int.TryParse(policyModule.Order.ToString(), out value))
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid Order");
            }

            List <string> successCodes = new List <string>();

            foreach (var successCode in softwareModule.SuccessCodes.Split(','))
            {
                successCodes.Add(successCode);
            }

            if (successCodes.Count == 0)
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid Success Code");
            }

            if (successCodes.Any(code => !int.TryParse(code, out value)))
            {
                return("Software Module: " + softwareModule.Name + " Has An Invalid Success Code");
            }

            var uploadedFiles = new ServiceUploadedFile().GetFilesForModule(softwareModule.Guid);
            var externalFiles = new ServiceExternalDownload().GetForModule(softwareModule.Guid);

            if (uploadedFiles == null && externalFiles == null)
            {
                return("Software Module: " + softwareModule.Name + " Does Not Have Any Associated Files");
            }

            try
            {
                if (uploadedFiles.Count == 0 && externalFiles.Count == 0)
                {
                    return("Software Module: " + softwareModule.Name + " Does Not Have Any Associated Files");
                }
            }
            catch
            {
                return("Software Module: " + softwareModule.Name + " Error While Determining Associated Files");
            }

            var basePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "software_uploads");

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    try
                    {
                        foreach (var file in uploadedFiles.OrderBy(x => x.Name))
                        {
                            if (string.IsNullOrEmpty(file.Hash))
                            {
                                return("Software Module: " + softwareModule.Name + " " + file.Name + " Does Not Have An MD5 Hash");
                            }
                            var fullPath = Path.Combine(basePath, file.Guid, file.Name);
                            if (!File.Exists(fullPath))
                            {
                                return("Software Module: " + softwareModule.Name + " " + fullPath + " Does Not Exist");
                            }
                        }


                        foreach (var file in externalFiles.OrderBy(x => x.FileName))
                        {
                            if (file.Status != EnumFileDownloader.DownloadStatus.Complete)
                            {
                                return("Software Module: " + softwareModule.Name + " " + file.FileName + " Has Not Finished Downloading Or Is In An Error State");
                            }
                            if (string.IsNullOrEmpty(file.Md5Hash))
                            {
                                return("Software Module: " + softwareModule.Name + " " + file.FileName + " Does Not Have An MD5 Hash");
                            }
                            var fullPath = Path.Combine(basePath, file.ModuleGuid, file.FileName);
                            if (!File.Exists(fullPath))
                            {
                                return("Software Module: " + softwareModule.Name + " " + fullPath + " Does Not Exist");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex.Message);
                        return("Software Module: " + softwareModule.Name + " Unknown Error Trying To Verify Files");
                    }
                }
                else
                {
                    return("Could Not Reach Storage Path");
                }
            }


            if (softwareModule.ImpersonationId != -1)
            {
                var impAccount = new ServiceImpersonationAccount().GetAccount(softwareModule.ImpersonationId);
                if (impAccount == null)
                {
                    return("Software Module: " + softwareModule.Name + " Has An Invalid Impersonation Account");
                }
            }

            return(null);
        }
Beispiel #22
0
        private string VerifyWindowsUpdate(EntityPolicyModules policyModule)
        {
            var wuModule = new ServiceWuModule().GetModule(policyModule.ModuleId);

            if (string.IsNullOrEmpty(wuModule.Name))
            {
                return("A Windows Update Module Has An Invalid Name");
            }
            if (wuModule.Archived)
            {
                return("Windows Update Module: " + wuModule.Name + " Is Archived");
            }
            if (string.IsNullOrEmpty(wuModule.Guid))
            {
                return("Windows Update Module: " + wuModule.Name + " Has An Invalid GUID");
            }

            int value;

            if (!int.TryParse(wuModule.Timeout.ToString(), out value))
            {
                return("Windows Update Module: " + wuModule.Name + " Has An Invalid Timeout");
            }

            if (!int.TryParse(policyModule.Order.ToString(), out value))
            {
                return("Windows Update Module: " + wuModule.Name + " Has An Invalid Order");
            }

            List <string> successCodes = new List <string>();

            foreach (var successCode in wuModule.SuccessCodes.Split(','))
            {
                successCodes.Add(successCode);
            }

            if (successCodes.Count == 0)
            {
                return("Windows Update Module: " + wuModule.Name + " Has An Invalid Success Code");
            }

            if (successCodes.Any(code => !int.TryParse(code, out value)))
            {
                return("Windows Update Module: " + wuModule.Name + " Has An Invalid Success Code");
            }

            var uploadedFiles = new ServiceUploadedFile().GetFilesForModule(wuModule.Guid);
            var externalFiles = new ServiceExternalDownload().GetForModule(wuModule.Guid);

            if (uploadedFiles == null && externalFiles == null)
            {
                return("Windows Update Module: " + wuModule.Name + " Does Not Have Any Associated Files");
            }

            try
            {
                if (uploadedFiles.Count == 0 && externalFiles.Count == 0)
                {
                    return("Windows Update Module: " + wuModule.Name + " Does Not Have Any Associated Files");
                }
            }
            catch
            {
                return("Windows Update Module: " + wuModule.Name + " Error While Determining Associated Files");
            }

            var firstExtension    = "";
            int uploadFileCounter = 0;

            foreach (var file in uploadedFiles)
            {
                var ext = Path.GetExtension(file.Name);
                if (ext == null)
                {
                    return("Windows Update Module: " + wuModule.Name + " Has An Invalid File Extension In The Uploaded Files List");
                }
                if (!ext.ToLower().Equals(".cab") && !ext.ToLower().Equals(".msu"))
                {
                    return("Windows Update Module: " + wuModule.Name + " Has An Invalid File Extension In The Uploaded Files List");
                }
                if (uploadFileCounter == 0)
                {
                    firstExtension = ext;
                }
                else
                {
                    if (!firstExtension.Equals(ext))
                    {
                        return("Windows Update Module: " + wuModule.Name + " All Files Per Windows Update Module Must Be The Same Type.  IE. All .msu Or All .cab");
                    }
                }

                uploadFileCounter++;
            }

            int externalFileCounter = 0;

            foreach (var file in externalFiles)
            {
                var ext = Path.GetExtension(file.FileName);
                if (ext == null)
                {
                    return("Windows Update Module: " + wuModule.Name + " Has An Invalid File Extension In The External Files List");
                }
                if (!ext.ToLower().Equals(".cab") && !ext.ToLower().Equals(".msu"))
                {
                    return("Windows Update Module: " + wuModule.Name + " Has An Invalid File Extension In The External Files List");
                }
                if (uploadFileCounter == 0 && string.IsNullOrEmpty(firstExtension)) //don't overwrite extension that may have been set in uploaded files
                {
                    firstExtension = ext;
                }
                else
                {
                    if (!firstExtension.Equals(ext))
                    {
                        return("Windows Update Module: " + wuModule.Name + " All Files Per Windows Update Module Must Be The Same Type.  IE. All .msu Or All .cab");
                    }
                }

                externalFileCounter++;
            }



            var basePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "software_uploads");

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    try
                    {
                        foreach (var file in uploadedFiles.OrderBy(x => x.Name))
                        {
                            if (string.IsNullOrEmpty(file.Hash))
                            {
                                return("Windows Update Module: " + wuModule.Name + " " + file.Name + " Does Not Have An MD5 Hash");
                            }
                            var fullPath = Path.Combine(basePath, file.Guid, file.Name);
                            if (!File.Exists(fullPath))
                            {
                                return("Windows Update Module: " + wuModule.Name + " " + fullPath + " Does Not Exist");
                            }
                        }


                        foreach (var file in externalFiles.OrderBy(x => x.FileName))
                        {
                            if (file.Status != EnumFileDownloader.DownloadStatus.Complete)
                            {
                                return("Windows Update Module: " + wuModule.Name + " " + file.FileName + " Has Not Finished Downloading Or Is In An Error State");
                            }
                            if (string.IsNullOrEmpty(file.Md5Hash))
                            {
                                return("Windows Update Module: " + wuModule.Name + " " + file.FileName + " Does Not Have An MD5 Hash");
                            }
                            var fullPath = Path.Combine(basePath, file.ModuleGuid, file.FileName);
                            if (!File.Exists(fullPath))
                            {
                                return("Windows Update Module: " + wuModule.Name + " " + fullPath + " Does Not Exist");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex.Message);
                        return("Windows Update Module: " + wuModule.Name + " Unknown Error Trying To Verify Files");
                    }
                }
                else
                {
                    return("Could Not Reach Storage Path");
                }
            }

            return(null);
        }