// Don't change the case of this method, since ngit does reflection on it public bool setExecutable(bool exec) { try { UnixFileInfo fi = new UnixFileInfo(path); FileAccessPermissions perms = fi.FileAccessPermissions; if ((perms & FileAccessPermissions.UserRead) != 0) { perms |= FileAccessPermissions.UserExecute; } if ((perms & FileAccessPermissions.OtherRead) != 0) { perms |= FileAccessPermissions.OtherExecute; } if ((perms & FileAccessPermissions.GroupRead) != 0) { perms |= FileAccessPermissions.GroupExecute; } fi.FileAccessPermissions = perms; return(true); } catch { return(false); } }
private void CreateSymlink(string linkName) { if (File.Exists(linkName)) { try { File.Delete(linkName); } catch (Exception e) { throw new RecoverableException(string.Format("There was an error when removing existing `{0}' symlink: {1}", linkName, e.Message)); } } try { var slavePtyFile = new UnixFileInfo(ptyStream.SlaveName); symlink = slavePtyFile.CreateSymbolicLink(linkName); } catch (Exception e) { throw new RecoverableException(string.Format("There was an error when when creating a symlink `{0}': {1}", linkName, e.Message)); } Logger.Log(LogLevel.Info, "Created a Slip Radio pty connection to {0}", linkName); }
public static FileSystemObject FileSystemInfoToFileSystemObject(FileSystemInfo fileInfo, bool downloadCloud = false, bool INCLUDE_CONTENT_HASH = false) { FileSystemObject obj = null; try { if (fileInfo is DirectoryInfo) { obj = new FileSystemObject() { Path = fileInfo.FullName, Permissions = FileSystemUtils.GetFilePermissions(fileInfo), IsDirectory = true }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; } } else { obj = new FileSystemObject() { Path = fileInfo.FullName, Permissions = FileSystemUtils.GetFilePermissions(fileInfo), Size = (ulong)(fileInfo as FileInfo).Length, IsDirectory = false }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(fileInfo.FullName); obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(fileInfo.FullName); } else { obj.SignatureStatus = "Cloud"; } } } if (INCLUDE_CONTENT_HASH) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { if (obj.Permissions.Contains("Execute")) { obj.IsExecutable = true; } } else { try { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.IsExecutable = true; } } } catch (System.UnauthorizedAccessException ex) { Log.Verbose(ex, "Couldn't access {0} to check if signature is needed.", fileInfo.FullName); } } } } catch (System.UnauthorizedAccessException e) { Log.Verbose(e, "Access Denied {0}", fileInfo?.FullName); } catch (System.IO.IOException e) { Log.Verbose(e, "Couldn't parse {0}", fileInfo?.FullName); } catch (Exception e) { Log.Warning(e, "Error collecting file system information: {0}", e.Message); } return(obj); }
public void SetUnixFilePermissions(string filePath, int permissions) { var unixFileInfo = new UnixFileInfo(filePath); unixFileInfo.FileAccessPermissions = (FileAccessPermissions)permissions; }
public static void CreateSymlink(string SourcePath, string DestinationPath) { UnixFileInfo fileinfo = new UnixFileInfo(SourcePath); fileinfo.CreateSymbolicLink(DestinationPath); }
public void Delete(SafeUri uri) { UnixFileInfo info = new UnixFileInfo(uri.LocalPath); info.Delete(); }
/// <summary> /// Starts the updating process. /// </summary> /// <returns>TRUE if successful; If FALSE use Updater.LastError to get the error</returns> public static bool Update() { if (!IsAppImage) { logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", "This app is not packaged in an AppImage")); return(false); } if (!ready) { logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", "Updater is not ready yet")); return(false); } // First, create a backup logs.Add(new LogMessage(Logseverity.Info, "Updater.Update", "Creating backup")); try { File.Copy(AppImagePath, AppImagePath + "~", true); } catch (Exception ex) { // I'd be very suprised if this throws an exception logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", $"An exception of type {ex.GetType()} was thrown, this is most likely an internal library error", ex)); return(false); } // Mark as executable logs.Add(new LogMessage(Logseverity.Info, "Updater.Update", "Marking as executable")); try { var _file = UnixFileInfo.GetFileSystemEntry(downloadPath); // This will do for now... _file.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute; } catch (Exception ex) { logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", $"An exception of type {ex.GetType()} was thrown, this is most likely an internal library error", ex)); return(false); } // Then overwrite logs.Add(new LogMessage(Logseverity.Info, "Updater.Update", "Overwriting")); try { File.Delete(AppImagePath); File.Move(downloadPath, AppImagePath); } catch (Exception ex) { logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", $"An exception of type {ex.GetType()} was thrown, this is most likely an internal library error", ex)); return(false); } // Delete backups logs.Add(new LogMessage(Logseverity.Info, "Updater.Update", "Deleting backup")); try { File.Delete(AppImagePath + "~"); } catch (Exception ex) { logs.Add(new LogMessage(Logseverity.Error, "Updater.Update", $"An exception of type {ex.GetType()} was thrown, this is most likely an internal library error", ex)); return(false); } logs.Add(new LogMessage(Logseverity.Info, "Updater.Update", "Done, restarting the app is recommended")); return(true); }
// Don't change the case of this method, since ngit does reflection on it public bool canExecute() { UnixFileInfo fi = new UnixFileInfo (path); if (!fi.Exists) return false; return 0 != (fi.FileAccessPermissions & (FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute)); }
public static bool HasFilePermission(string path, FileAccessPermissions fap) { var fi = new UnixFileInfo(path); return(HasPermission(fi, fap)); }
private void SetUAttributes(UnixFileInfo ufi) { ufi.FileSpecialAttributes = (Mono.Unix.FileSpecialAttributes) this.Attributes; }
/*public void CloseStream(){ * if(fd > 0) * Syscall.close(fd); * }*/ private int GetUAttributes(UnixFileInfo fi) { return((int)fi.FileSpecialAttributes); }
private static void RegisterProtocol() { // we really should query the user for this, but since Dialogs appear to be completely f****d, we're going // to just install it right now. var xdg_path = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "applications"); var xdg_file = Path.Join(xdg_path, "aucapture-opener.desktop"); if (!File.Exists(xdg_file)) { var executingassmb = System.Reflection.Assembly.GetExecutingAssembly().Location; Console.WriteLine(executingassmb); if (Path.HasExtension("dll")) { executingassmb = "dotnet " + executingassmb; } else { executingassmb = Process.GetCurrentProcess().MainModule.FileName; Console.WriteLine(executingassmb); } var xdg_file_write = new string[] { "[Desktop Entry]", "Type=Application", "Name=aucapture URI Handler", $"Exec={executingassmb} %u", "StartupNotify=false", "MimeType=x-scheme-handler/aucapture;" }; using (var file = File.CreateText(xdg_file)) { foreach (string str in xdg_file_write) { file.WriteLine(str); } } var xdg_posix = new UnixFileInfo(xdg_file); xdg_posix.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute; // Finally, register with xdg-mime. var xdgproc = new Process() { StartInfo = new ProcessStartInfo { FileName = "/usr/bin/xdg-mime", Arguments = $"default aucapture-opener.desktop x-scheme-handler/aucapture", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, } }; xdgproc.Start(); string result = xdgproc.StandardOutput.ReadToEnd(); xdgproc.WaitForExit(); } }
public static string GetFilePermissions(FileSystemInfo fileInfo) { if (fileInfo != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var filename = fileInfo.FullName; FileAccessPermissions permissions = default(FileAccessPermissions); if (fileInfo is FileInfo) { try { permissions = new UnixFileInfo(filename).FileAccessPermissions; } catch (IOException ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else if (fileInfo is DirectoryInfo) { try { permissions = new UnixDirectoryInfo(filename).FileAccessPermissions; } catch (IOException ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else { return(null); } return(permissions.ToString()); } else { FileSystemSecurity fileSecurity = null; var filename = fileInfo.FullName; if (filename.Length >= 260 && !filename.StartsWith(@"\\?\")) { filename = $"\\?{filename}"; } if (fileInfo is FileInfo) { try { fileSecurity = new FileSecurity(filename, AccessControlSections.All); } catch (UnauthorizedAccessException) { Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName); } catch (InvalidOperationException) { Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName); } catch (FileNotFoundException) { Log.Verbose("File not found to get permissions {0}.", fileInfo.FullName); } catch (ArgumentException) { Log.Debug("Filename not valid for getting permissions {0}", fileInfo.FullName); } catch (Exception e) { Log.Debug(e, $"Error with {fileInfo.FullName}"); } } else if (fileInfo is DirectoryInfo) { try { fileSecurity = new DirectorySecurity(filename, AccessControlSections.All); } catch (UnauthorizedAccessException) { Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName); } catch (InvalidOperationException) { Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName); } catch (Exception e) { Log.Debug(e, $"Error with {fileInfo.FullName}"); } } else { return(null); } if (fileSecurity != null) { return(fileSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All)); } else { return(""); } } } return(""); }
protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration) { var proj = item as MonoMacProject; if (proj == null || proj.CompileTarget != CompileTarget.Exe) { return(base.Build(monitor, item, configuration)); } var conf = (MonoMacProjectConfiguration)configuration.GetConfiguration(item); var resDir = conf.AppDirectory.Combine("Contents", "Resources"); var appDir = conf.AppDirectory; //make sure the codebehind files are updated before building var res = MacBuildUtilities.UpdateCodeBehind(monitor, proj.CodeBehindGenerator, proj.Files); if (res.ErrorCount > 0) { return(res); } res = res.Append(base.Build(monitor, item, configuration)); if (res.ErrorCount > 0) { return(res); } //copy exe, mdb, refs, copy-to-output, Content files to Resources var filesToCopy = GetCopyFiles(proj, configuration, conf).Where(NeedsBuilding).ToList(); if (filesToCopy.Count > 0) { monitor.BeginTask("Copying resource files to app bundle", filesToCopy.Count); foreach (var f in filesToCopy) { f.EnsureOutputDirectory(); File.Copy(f.Input, f.Output, true); monitor.Log.WriteLine("Copied {0}", f.Output.ToRelative(appDir)); monitor.Step(1); } monitor.EndTask(); } if (!PropertyService.IsMac) { res.AddWarning("Cannot compile xib files on non-Mac platforms"); } else { //Interface Builder files if (res.Append(MacBuildUtilities.CompileXibFiles(monitor, proj.Files, resDir)).ErrorCount > 0) { return(res); } } //info.plist var plistOut = conf.AppDirectory.Combine("Contents", "Info.plist"); var appInfoIn = proj.Files.GetFile(proj.BaseDirectory.Combine("Info.plist")); if (new FilePair(proj.FileName, plistOut).NeedsBuilding() || (appInfoIn != null && new FilePair(appInfoIn.FilePath, plistOut).NeedsBuilding())) { if (res.Append(MergeInfoPlist(monitor, proj, conf, appInfoIn, plistOut)).ErrorCount > 0) { return(res); } } //launch script var ls = conf.LaunchScript; if (!File.Exists(ls)) { if (!Directory.Exists(ls.ParentDirectory)) { Directory.CreateDirectory(ls.ParentDirectory); } var src = AddinManager.CurrentAddin.GetFilePath("MonoMacLaunchScript.sh"); File.Copy(src, ls, true); var fi = new UnixFileInfo(ls); fi.FileAccessPermissions |= FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; } //pkginfo var pkgInfo = conf.AppDirectory.Combine("Contents", "PkgInfo"); if (!File.Exists(pkgInfo)) { using (var f = File.OpenWrite(pkgInfo)) f.Write(new byte [] { 0X41, 0X50, 0X50, 0X4C, 0x3f, 0x3f, 0x3f, 0x3f }, 0, 8); // "APPL???" } return(res); }
public static string CollectFilePermissionInformation(string filePath) { var bldr = new StringBuilder(); try { if (Platform.IsWindows) { var currentUser = WindowsIdentity.GetCurrent(); bldr.AppendLine($"current user is {currentUser.Name}"); var principal = new WindowsPrincipal(currentUser); bool isInRoleWithAccess = false; bool accessDenied = false; bool accessAllowed = false; FileSystemRights accessRights = FileSystemRights.Write; var acl = File.GetAccessControl(filePath); var rules = acl.GetAccessRules(true, true, typeof(NTAccount)); var sid = acl.GetOwner(typeof(SecurityIdentifier)); var acct = sid.Translate(typeof(NTAccount)) as NTAccount; if (acct != null) { bldr.AppendLine($"owner of \"{filePath}\" is {acct.Value}"); } var fileAttributes = RobustFile.GetAttributes(filePath); bldr.AppendLine($"{filePath} current ReadOnly attribute of {filePath} is {(fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly}"); foreach (AuthorizationRule rule in rules) { var fsAccessRule = rule as FileSystemAccessRule; if (fsAccessRule == null) { continue; } if ((fsAccessRule.FileSystemRights & accessRights) > 0) { var ntAccount = rule.IdentityReference as NTAccount; if (ntAccount == null) { continue; } if (principal.IsInRole(ntAccount.Value)) { if (fsAccessRule.AccessControlType == AccessControlType.Deny) { bldr.AppendLine($"current user is denied write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}"); accessDenied = true; } if (fsAccessRule.AccessControlType == AccessControlType.Allow) { bldr.AppendLine($"current user is allowed write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}"); accessAllowed = true; } isInRoleWithAccess = true; } } } if (isInRoleWithAccess) { if (!accessAllowed) { bldr.AppendLine($"current user is not explicitly allowed write access to {filePath}"); } if (!accessDenied) { bldr.AppendLine($"current user is not explicitly denied write access to {filePath}"); } } else { bldr.AppendLine($"current user is not explicitly given access to {filePath}"); } } else { var folder = Path.GetDirectoryName(filePath); var fileInfo = new UnixFileInfo(filePath); var dirInfo = new UnixDirectoryInfo(folder); var userInfo = UnixUserInfo.GetRealUser(); bldr.AppendLine($"current user is {userInfo.UserName}"); bldr.AppendLine($"owner of \"{filePath}\" is {fileInfo.OwnerUser.UserName}"); bldr.AppendLine($"permissions of \"{filePath}\" = {fileInfo.FileAccessPermissions.ToString()}"); bldr.AppendLine($"owner of \"{folder}\" is {dirInfo.OwnerUser.UserName}"); bldr.AppendLine($"permissions of \"{folder}\" = {dirInfo.FileAccessPermissions.ToString()}"); } } catch (Exception e) { bldr.AppendLine($"Caught exception {e} while trying to collect information about {filePath}"); } return(bldr.ToString()); }
private static void ExtractTarByEntry(Stream inputStream, string targetDir, bool asciiTranslate, Action <long, long> progress) { TarInputStream tarIn = new TarInputStream(inputStream); TarEntry tarEntry; while ((tarEntry = tarIn.GetNextEntry()) != null) { if (tarEntry.IsDirectory) { continue; } progress(tarIn.Position, tarIn.Length); // Converts the unix forward slashes in the filenames to windows backslashes string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar); // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine if (Path.IsPathRooted(name)) { name = name.Substring(Path.GetPathRoot(name).Length); } // Apply further name transformations here as necessary string outName = Path.Combine(targetDir, name).NormalizePath(); string directoryName = Path.GetDirectoryName(outName); // Does nothing if directory exists Directory.CreateDirectory(directoryName); if (tarEntry.TarHeader.TypeFlag != '0') { switch ((char)tarEntry.TarHeader.TypeFlag) { case '1': if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT) { Platform.CreateHardLinkWin32(outName.NormalizePath(), Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath(), !tarEntry.IsDirectory); } else { var symLinkInfo = new UnixSymbolicLinkInfo(Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath()); symLinkInfo.CreateLink(outName); } break; case '2': if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT) { Platform.CreateSymbolicLinkWin32(outName.NormalizePath(), tarEntry.TarHeader.LinkName, !tarEntry.IsDirectory); } else { var symLinkInfo = new UnixSymbolicLinkInfo(outName.NormalizePath()); symLinkInfo.CreateSymbolicLinkTo(tarEntry.TarHeader.LinkName); } break; } } else { try { using (var outStr = new FileStream(outName, FileMode.Create)) { if (asciiTranslate) { CopyWithAsciiTranslate(tarIn, outStr); } else { tarIn.CopyEntryContents(outStr); } } if (Platform.PlatformIdentifier == Platforms.PlatformID.Unix || Platform.PlatformIdentifier == Platforms.PlatformID.MacOSX) { var unixFileInfo = new UnixFileInfo(outName) { FileAccessPermissions = (FileAccessPermissions)tarEntry.TarHeader.Mode }; } // Set the modification date/time. This approach seems to solve timezone issues. DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc); File.SetLastWriteTime(outName, myDt); } catch (Exception) { } } } tarIn.Close(); }
public static bool Setup(string filename = null) { JsonSerializer.SetDefaultResolver(StandardResolver.ExcludeNull); if (filename != null) { if (_SqliteFilename != filename) { if (Connection != null) { CloseDatabase(); } _SqliteFilename = filename; } } if (Connection == null) { WriteQueue = new ConcurrentQueue <WriteObject>(); Connection = new SQLiteConnection($"Data Source=" + _SqliteFilename); Connection.Open(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var unixFileInfo = new UnixFileInfo(_SqliteFilename); // set file permission to 666 unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupWrite | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherWrite; } using (var cmd = new SQLiteCommand(SQL_CREATE_RUNS, Connection, Transaction)) { cmd.ExecuteNonQuery(); cmd.CommandText = PRAGMAS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_ROW_KEY_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_TYPE_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_KEY_IDENTITY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_LEVEL_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_IDENTITY_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FILE_MONITORED; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_PERSISTED_SETTINGS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_DEFAULT_SETTINGS; cmd.Parameters.AddWithValue("@schema_version", SCHEMA_VERSION); FirstRun &= cmd.ExecuteNonQuery() != 0; } Commit(); if (!WriterStarted) { ((Action)(async() => { await Task.Run(() => KeepSleepAndFlushQueue()).ConfigureAwait(false); }))(); WriterStarted = true; } return(true); } return(false); }
public static void CreateArchive(ProgressMonitor mon, string folder, string targetFile) { string tf = Path.GetFileNameWithoutExtension(targetFile); if (tf.EndsWith(".tar")) { tf = Path.GetFileNameWithoutExtension(tf); } if (File.Exists(targetFile)) { File.Delete(targetFile); } using (Stream os = File.Create(targetFile)) { Stream outStream = os; // Create the zip file switch (GetArchiveExtension(targetFile)) { case ".tar.gz": outStream = new GZipOutputStream(outStream); goto case ".tar"; case ".tar.bz2": outStream = new BZip2OutputStream(outStream, 9); goto case ".tar"; case ".tar": TarArchive archive = TarArchive.CreateOutputTarArchive(outStream); archive.SetAsciiTranslation(false); archive.RootPath = folder; archive.ProgressMessageEvent += delegate(TarArchive ac, TarEntry e, string message) { if (message != null) { mon.Log.WriteLine(message); } }; foreach (FilePath f in GetFilesRec(new DirectoryInfo(folder))) { TarEntry entry = TarEntry.CreateEntryFromFile(f); entry.Name = f.ToRelative(folder); if (!Platform.IsWindows) { UnixFileInfo fi = new UnixFileInfo(f); entry.TarHeader.Mode = (int)fi.Protection; } else { entry.Name = entry.Name.Replace('\\', '/'); FilePermissions p = FilePermissions.S_IFREG | FilePermissions.S_IROTH | FilePermissions.S_IRGRP | FilePermissions.S_IRUSR; if (!new FileInfo(f).IsReadOnly) { p |= FilePermissions.S_IWUSR; } entry.TarHeader.Mode = (int)p; } archive.WriteEntry(entry, false); } // HACK: GNU tar expects to find a double zero record at the end of the archive. TarArchive only emits one. // This hack generates the second zero block. FieldInfo tarOutField = typeof(TarArchive).GetField("tarOut", BindingFlags.Instance | BindingFlags.NonPublic); if (tarOutField != null) { TarOutputStream tarOut = (TarOutputStream)tarOutField.GetValue(archive); tarOut.Finish(); } archive.CloseArchive(); break; case ".zip": ZipOutputStream zs = new ZipOutputStream(outStream); zs.SetLevel(5); byte[] buffer = new byte [8092]; foreach (FilePath f in GetFilesRec(new DirectoryInfo(folder))) { string name = f.ToRelative(folder); if (Platform.IsWindows) { name = name.Replace('\\', '/'); } ZipEntry infoEntry = new ZipEntry(name); zs.PutNextEntry(infoEntry); using (Stream s = File.OpenRead(f)) { int nr; while ((nr = s.Read(buffer, 0, buffer.Length)) > 0) { zs.Write(buffer, 0, nr); } } zs.CloseEntry(); } zs.Finish(); zs.Close(); break; default: mon.Log.WriteLine("Unsupported file format: " + Path.GetFileName(targetFile)); return; } } }
private static void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { Console.WriteLine("-- Download Done --"); if (!string.IsNullOrWhiteSpace(_param.CheckSum) && !IsFileChecksumOK(_tempFile, _param)) { Console.WriteLine("-- Checksum Error --"); UpdateErrorEvent?.Invoke(new UpdateErrorEventArgs { Message = "CheckSum Error" }); return; } var cd = _webClient.ResponseHeaders["Content-Disposition"] != null ? new ContentDisposition(_webClient.ResponseHeaders["Content-Disposition"]) : null; var filename = string.IsNullOrEmpty(cd?.FileName) ? Path.GetFileName(_webClient.ResponseUri.LocalPath) : cd.FileName; var tempPath = Path.Combine(Path.GetTempPath(), filename); if (File.Exists(tempPath)) { File.Delete(tempPath); } File.Move(_tempFile, tempPath); Console.WriteLine("-- File Moved To : " + tempPath + " --"); var ext = Path.GetExtension(tempPath); if (ext.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { var zipExtractorPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ZipExtractor"); var zipExtractor = ""; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.X64) { zipExtractor = Path.Combine(zipExtractorPath, "win64", "ZipExtractorCore.exe"); Console.WriteLine("ZipExtractor - " + zipExtractor); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.X86) { zipExtractor = Path.Combine(zipExtractorPath, "win32", "ZipExtractorCore.exe"); Console.WriteLine("ZipExtractor - " + zipExtractor); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSArchitecture == Architecture.Arm) { zipExtractor = Path.Combine(zipExtractorPath, "win-arm", "ZipExtractorCore.exe"); Console.WriteLine("ZipExtractor - " + zipExtractor); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && RuntimeInformation.OSArchitecture == Architecture.X64) { zipExtractor = Path.Combine(zipExtractorPath, "linux64", "ZipExtractorCore"); Console.WriteLine("ZipExtractor - " + zipExtractor); var unixFileInfo = new UnixFileInfo(zipExtractor); unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && RuntimeInformation.OSArchitecture == Architecture.Arm) { zipExtractor = Path.Combine(zipExtractorPath, "linux-arm", "ZipExtractorCore"); Console.WriteLine("ZipExtractor - " + zipExtractor); var unixFileInfo = new UnixFileInfo(zipExtractor); unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && RuntimeInformation.OSArchitecture == Architecture.X64) { zipExtractor = Path.Combine(zipExtractorPath, "osx64", "ZipExtractorCore"); Console.WriteLine("ZipExtractor - " + zipExtractor); var unixFileInfo = new UnixFileInfo(zipExtractor); unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute; } // dotnet core will use dll, rename to exe var exeFile = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe", StringComparison.OrdinalIgnoreCase); var exePath = Path.GetDirectoryName(exeFile); var args = $"-exeFile=\"{exeFile}\" -exePath=\"{exePath}\" -zipFile=\"{tempPath}\""; var psi = new ProcessStartInfo { FileName = zipExtractor, UseShellExecute = true, Arguments = args }; Process.Start(psi); UpdateDownloadedEvent?.Invoke(new UpdateDownloadedEventArgs { IsDownloaded = true }); return; } UpdateErrorEvent?.Invoke(new UpdateErrorEventArgs { Message = "Only Zip Files Allowed" }); return; }
public static string GetFilePermissions(FileSystemInfo fileInfo) { if (fileInfo != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var filename = fileInfo.FullName; FileAccessPermissions permissions = default(FileAccessPermissions); try { if (fileInfo is FileInfo) { permissions = new UnixFileInfo(filename).FileAccessPermissions; } else if (fileInfo is DirectoryInfo) { permissions = new UnixDirectoryInfo(filename).FileAccessPermissions; } } catch (Exception e) when( e is IOException || e is InvalidOperationException ) { Log.Verbose("Unable to get access control for {0}: {1}", fileInfo.FullName, e.GetType().ToString()); } catch (Exception e) { Log.Debug($"Error Getting File Permissions {e.GetType().ToString()}"); } return(permissions.ToString()); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var filename = fileInfo.FullName; if (filename.Length >= 260 && !filename.StartsWith(@"\\?\")) { filename = $"\\?{filename}"; } try { if (fileInfo is FileInfo) { return(new FileSecurity(filename, AccessControlSections.All).GetSecurityDescriptorSddlForm(AccessControlSections.All)); } else if (fileInfo is DirectoryInfo) { return(new DirectorySecurity(filename, AccessControlSections.All).GetSecurityDescriptorSddlForm(AccessControlSections.All)); } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { var InfoType = fileInfo is FileInfo ? "FileSecurity" : "DirectorySecurity"; Log.Verbose($"Error parsing {InfoType} for {fileInfo.FullName} {e.GetType().ToString()}"); } catch (Exception e) { Log.Debug($"Error Getting File Permissions {e.GetType().ToString()}"); } return(string.Empty); } } return(string.Empty); }
// Don't change the case of this method, since ngit does reflection on it public bool setExecutable(bool exec) { try { UnixFileInfo fi = new UnixFileInfo (path); FileAccessPermissions perms = fi.FileAccessPermissions; if ((perms & FileAccessPermissions.UserRead) != 0) perms |= FileAccessPermissions.UserExecute; if ((perms & FileAccessPermissions.OtherRead) != 0) perms |= FileAccessPermissions.OtherExecute; if ((perms & FileAccessPermissions.GroupRead) != 0) perms |= FileAccessPermissions.GroupExecute; fi.FileAccessPermissions = perms; return true; } catch { return false; } }
/// <summary> /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file /// </summary> /// <param name="fileInfo">A reference to a file on disk.</param> /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param> /// <param name="INCLUDE_CONTENT_HASH">If we should generate a hash of the file.</param> /// <returns></returns> public static FileSystemObject FileSystemInfoToFileSystemObject(FileSystemInfo fileInfo, bool downloadCloud = false, bool INCLUDE_CONTENT_HASH = false) { if (fileInfo == null) { return(null); } FileSystemObject obj = new FileSystemObject() { Path = fileInfo.FullName, PermissionsString = FileSystemUtils.GetFilePermissions(fileInfo), }; // Get Owner/Group if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { var fileSecurity = new FileSecurity(fileInfo.FullName, AccessControlSections.All); IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier)); IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier)); // Set the Owner and Group to the SID, in case we can't properly translate obj.Owner = oid.ToString(); obj.Group = gid.ToString(); try { // Translate owner into the string representation. obj.Owner = (oid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { Log.Verbose("Couldn't find the Owner from SID {0} for file {1}", oid.ToString(), fileInfo.FullName); } try { // Translate group into the string representation. obj.Group = (gid.Translate(typeof(NTAccount)) as NTAccount).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. Log.Verbose("Couldn't find the Group from SID {0} for file {1}", gid.ToString(), fileInfo.FullName); } var rules = fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); foreach (FileSystemAccessRule rule in rules) { string name = rule.IdentityReference.Value; try { name = rule.IdentityReference.Translate(typeof(NTAccount)).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. } foreach (var permission in rule.FileSystemRights.ToString().Split(',')) { obj.Permissions.Add(new KeyValuePair <string, string>(name, permission)); } } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("User", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Execute")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Execute")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Execute")); } else { foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("User", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("User", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("User", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("User", permission.Trim().Substring(4))); } } foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("Group", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Group", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("Group", permission.Trim().Substring(5))); } } foreach (var permission in file.FileAccessPermissions.ToString().Split(',').Where((x) => x.Trim().StartsWith("Other", StringComparison.InvariantCulture))) { if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture)) { obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Read")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Write")); obj.Permissions.Add(new KeyValuePair <string, string>("Other", "Execute")); } else { obj.Permissions.Add(new KeyValuePair <string, string>("Other", permission.Trim().Substring(5))); } } } } catch (Exception e) when( e is ArgumentNullException || e is ArgumentException) { Log.Verbose($"Failed to get permissions for {fileInfo.FullName} {e.GetType().ToString()}"); } } if (fileInfo is DirectoryInfo) { obj.IsDirectory = true; } else if (fileInfo is FileInfo) { obj.Size = (ulong)(fileInfo as FileInfo).Length; obj.IsDirectory = false; if (INCLUDE_CONTENT_HASH) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } // Set IsExecutable and Signature Status if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(fileInfo.FullName); obj.Characteristics.AddRange(WindowsFileSystemUtils.GetDllCharacteristics(fileInfo.FullName)); obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path); } } return(obj); }
public static UnixDriveInfo GetDriveInfo(this UnixFileInfo fileInfo) { Mono.Unix.UnixDirectoryInfo file = new Mono.Unix.UnixDirectoryInfo(fileInfo.FullName); Mono.Unix.UnixDriveInfo drive = new Mono.Unix.UnixDriveInfo(fileInfo.FullName); return(drive); }
public UnixMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { UnixFileInfo fileInfo = null; bool fileExists = false; try { fileInfo = new UnixFileInfo(fileName); fileExists = fileInfo.Exists; } catch { } int fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); if (fd == -1) { if (Stdlib.GetLastError() == Errno.ENOENT && parameters.CreateDirs) { string dirName = Path.GetDirectoryName(fileName); if (!Directory.Exists(dirName) && parameters.CreateDirs) { Directory.CreateDirectory(dirName); } fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); } } if (fd == -1) { UnixMarshal.ThrowExceptionForLastError(); } try { _file = new UnixStream(fd, true); long filePosition = _file.Position; if (fileExists || filePosition > 0) { if (fileInfo != null) { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileInfo, (f) => File.GetCreationTimeUtc(f.FullName), (f) => { f.Refresh(); return(f.LastStatusChangeTimeUtc); }, (f) => DateTime.UtcNow).Value; } else { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileName, (f) => File.GetCreationTimeUtc(f), (f) => DateTime.UtcNow).Value; } } else { // We actually created the file and eventually concurrent processes CreationTimeUtc = DateTime.UtcNow; File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch { Syscall.close(fd); throw; } }
public override void Execute() { if (!CanRunOnPlatform()) { return; } Start(); if (roots == null || !roots.Any()) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { foreach (var driveInfo in DriveInfo.GetDrives()) { if (driveInfo.IsReady && driveInfo.DriveType == DriveType.Fixed) { roots.Add(driveInfo.Name); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { roots.Add("/"); // @TODO Improve this } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { roots.Add("/"); // @TODO Improve this } } foreach (var root in roots) { Log.Information("{0} root {1}", Strings.Get("Scanning"), root.ToString()); //Ensure the transaction is started to prevent collisions on the multithreaded code ahead _ = DatabaseManager.Transaction; try { var fileInfoEnumerable = DirectoryWalker.WalkDirectory(root); Parallel.ForEach(fileInfoEnumerable, (fileInfo => { try { FileSystemObject obj = null; if (fileInfo is DirectoryInfo) { obj = new FileSystemObject() { Path = fileInfo.FullName, Permissions = FileSystemUtils.GetFilePermissions(fileInfo), IsDirectory = true }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; } } else { obj = new FileSystemObject() { Path = fileInfo.FullName, Permissions = FileSystemUtils.GetFilePermissions(fileInfo), Size = (ulong)(fileInfo as FileInfo).Length, IsDirectory = false }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var file = new UnixFileInfo(fileInfo.FullName); obj.Owner = file.OwnerUser.UserName; obj.Group = file.OwnerGroup.GroupName; obj.SetGid = file.IsSetGroup; obj.SetUid = file.IsSetUser; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(fileInfo.FullName); obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(fileInfo.FullName); } else { obj.SignatureStatus = "Cloud"; } } } if (INCLUDE_CONTENT_HASH) { obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { if (obj.Permissions.Contains("Execute")) { obj.IsExecutable = true; } } else { try { if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud) { if (WindowsFileSystemUtils.NeedsSignature(obj.Path)) { obj.IsExecutable = true; } } } catch (System.UnauthorizedAccessException ex) { Log.Verbose(ex, "Couldn't access {0} to check if signature is needed.", fileInfo.FullName); } } } if (obj != null) { DatabaseManager.Write(obj, runId); if (examineCertificates && fileInfo.FullName.EndsWith(".cer", StringComparison.CurrentCulture) || fileInfo.FullName.EndsWith(".der", StringComparison.CurrentCulture) || fileInfo.FullName.EndsWith(".p7b", StringComparison.CurrentCulture)) { var certificate = X509Certificate.CreateFromCertFile(fileInfo.FullName); var certObj = new CertificateObject() { StoreLocation = fileInfo.FullName, StoreName = "Disk", CertificateHashString = certificate.GetCertHashString(), Subject = certificate.Subject, Pkcs7 = certificate.Export(X509ContentType.Cert).ToString() }; DatabaseManager.Write(certObj, runId); } } } catch (System.UnauthorizedAccessException e) { Log.Verbose(e, "Access Denied {0}", fileInfo?.FullName); } catch (System.IO.IOException e) { Log.Verbose(e, "Couldn't parse {0}", fileInfo?.FullName); } catch (Exception e) { Logger.DebugException(e); } })); } catch (Exception e) { Log.Warning(e, "Error collecting file system information: {0}", e.Message); } DatabaseManager.Commit(); } Stop(); }
private void onStartSync(object o, EventArgs args) { Hyena.Log.Debug("Start of Sync triggered!"); var options = View.GetOptions(); // target directory to copy to Hyena.Log.DebugFormat("Target folder is set to: {0}", options.TargetFolder); // count all files for progress bar int totalFiles = 0; foreach (var playlist in options.SelectedPlaylists) { totalFiles += playlist.Tracks.Count(); } View.Progress.Text = AddinManager.CurrentLocalizer.GetString("Preparing sync"); var progress_step = 1f / totalFiles; var current_progress = 0f; // begin sync worker thread ThreadStart syncStart = delegate() { Hyena.Log.Debug("Sync thread started!"); // foreach playlist foreach (var playlist in options.SelectedPlaylists) { Stream m3u_stream = null; StreamWriter m3u_writer = null; if (options.CreateM3u) { var m3u_fileUri = new StringBuilder().Append(options.TargetFolder) .Append(Path.DirectorySeparatorChar).Append(playlist.Name) .Append(".m3u").ToString(); m3u_stream = Banshee.IO.File.OpenWrite(new SafeUri(m3u_fileUri), true); Log.DebugFormat("opened m3u playlist for writing: {0}", m3u_fileUri); m3u_writer = new StreamWriter(m3u_stream, System.Text.Encoding.UTF8); } // for each contained file foreach (var track in playlist.Tracks) { // get filename part of path var dest_path_suffix = track.GetFilepathSuffix(options.SubfolderDepth); // we dont want %20 etc. in the m3u since some android devices delete // playlists with that encoding in it (i.e. galaxy S) Hyena.Log.DebugFormat("filename for m3u file is {0}", dest_path_suffix); // assemble new Uri of target track var destUri = new SafeUri(new StringBuilder().Append(options.TargetFolder) .Append(Path.DirectorySeparatorChar) .Append(dest_path_suffix).ToString()); // create subfolders if necessary string dest_path = options.TargetFolder; var folders = track.GetSubdirectories(options.SubfolderDepth); try { for (int i = 0; i < folders.Count(); i++) { dest_path += folders [i] + "/"; Hyena.Log.DebugFormat("creating folder {0}", dest_path); if (!Banshee.IO.Directory.Exists(dest_path)) { Banshee.IO.Directory.Create(new SafeUri(dest_path)); } } } catch { // folder creation failed, this is fatal, stop // TODO display a error popup break; } // copy file to selected folder try { var destExists = Banshee.IO.File.Exists(destUri); if (options.OverwriteExisting || !destExists) { if (options.CreateSymLinks) { var trackFilePath = SafeUri.UriToFilename(track.Uri); var destFilePath = SafeUri.UriToFilename(destUri); if (track.Uri.IsLocalPath) { var target = new UnixFileInfo(trackFilePath); // symbolic links need manual deletion, // otherwise an exception is thrown in CreateSymbolicLink() if (destExists) { var dest = new UnixFileInfo(destFilePath); dest.Delete(); } target.CreateSymbolicLink(destFilePath); } else { Hyena.Log.ErrorFormat("Cannot create symlink to remote path {0} in {1}, skipping", track.Uri, destFilePath); } } else { Banshee.IO.File.Copy(track.Uri, destUri, true); } Hyena.Log.DebugFormat("Copying {0} to {1}", track.Uri, destUri); } else { Hyena.Log.Debug("Not overwriting existing file {0}", destUri); } } catch { Hyena.Log.ErrorFormat("Error copying file {0} to {1}, skipping", track.Uri, destUri); } // increment the progressbar current_progress += progress_step; if (current_progress > 1.0f) { current_progress = 1.0f; } Gtk.Application.Invoke(delegate { View.Progress.Fraction = current_progress; View.Progress.Text = AddinManager.CurrentLocalizer.GetString("Copying") + " " + track.Filepath; Gtk.Main.IterationDo(false); }); if (options.CreateM3u) { m3u_writer.Write(track.CreateM3uEntry(options.SubfolderDepth)); } } // close the m3u file before processing next playlist if (options.CreateM3u) { Hyena.Log.Debug("closing m3u filedescriptor"); m3u_writer.Close(); m3u_writer.Dispose(); } Hyena.Log.Debug("sync process finished"); } Gtk.Application.Invoke(delegate { View.Progress.Text = AddinManager.CurrentLocalizer.GetString("Done!"); View.Progress.Fraction = 1f; Gtk.Main.IterationDo(false); }); Hyena.Log.Debug("sync DONE, returning"); return; }; // end of sync worker thread syncThread = new Thread(syncStart); syncThread.Start(); return; }
public void Open(string path) { var fs = new FileStream(path, FileMode.Open, FileAccess.Read); fs.Seek(0, SeekOrigin.Begin); byte[] hdrB = new byte[26]; fs.Read(hdrB, 0, 26); _header = Marshal.ByteArrayToStructureBigEndian <Header>(hdrB); Entry[] entries = new Entry[_header.entries]; for (int i = 0; i < _header.entries; i++) { byte[] entry = new byte[12]; fs.Read(entry, 0, 12); entries[i] = Marshal.ByteArrayToStructureBigEndian <Entry>(entry); } _creationTime = DateTime.UtcNow; _lastWriteTime = _creationTime; foreach (Entry entry in entries) { switch ((AppleSingleEntryID)entry.id) { case AppleSingleEntryID.DataFork: _dataFork = entry; break; case AppleSingleEntryID.FileDates: fs.Seek(entry.offset, SeekOrigin.Begin); byte[] datesB = new byte[16]; fs.Read(datesB, 0, 16); FileDates dates = Marshal.ByteArrayToStructureBigEndian <FileDates>(datesB); _creationTime = DateHandlers.MacToDateTime(dates.creationDate); _lastWriteTime = DateHandlers.MacToDateTime(dates.modificationDate); break; case AppleSingleEntryID.FileInfo: fs.Seek(entry.offset, SeekOrigin.Begin); byte[] finfo = new byte[entry.length]; fs.Read(finfo, 0, finfo.Length); if (_macintoshHome.SequenceEqual(_header.homeFilesystem)) { MacFileInfo macinfo = Marshal.ByteArrayToStructureBigEndian <MacFileInfo>(finfo); _creationTime = DateHandlers.MacToDateTime(macinfo.creationDate); _lastWriteTime = DateHandlers.MacToDateTime(macinfo.modificationDate); } else if (_proDosHome.SequenceEqual(_header.homeFilesystem)) { ProDOSFileInfo prodosinfo = Marshal.ByteArrayToStructureBigEndian <ProDOSFileInfo>(finfo); _creationTime = DateHandlers.MacToDateTime(prodosinfo.creationDate); _lastWriteTime = DateHandlers.MacToDateTime(prodosinfo.modificationDate); } else if (_unixHome.SequenceEqual(_header.homeFilesystem)) { UnixFileInfo unixinfo = Marshal.ByteArrayToStructureBigEndian <UnixFileInfo>(finfo); _creationTime = DateHandlers.UnixUnsignedToDateTime(unixinfo.creationDate); _lastWriteTime = DateHandlers.UnixUnsignedToDateTime(unixinfo.modificationDate); } else if (_dosHome.SequenceEqual(_header.homeFilesystem)) { DOSFileInfo dosinfo = Marshal.ByteArrayToStructureBigEndian <DOSFileInfo>(finfo); _lastWriteTime = DateHandlers.DosToDateTime(dosinfo.modificationDate, dosinfo.modificationTime); } break; case AppleSingleEntryID.ResourceFork: _rsrcFork = entry; break; } } fs.Close(); _opened = true; _isPath = true; _basePath = path; }
//private Stack<DatabaseTrackInfo> stk=new Stack<DatabaseTrackInfo>(); public void ImportSheet(CueSheet s) { if (import_manager == null) { try { import_manager = new LibraryImportManager(false); /*import_manager.ImportResult+=delegate(object sender,DatabaseImportResultArgs args) { * DatabaseTrackInfo trk=args.Track; * stk.Push (trk); * };*/ } catch (Exception ex) { Hyena.Log.Error(ex.ToString()); } } Hyena.Log.Debug("Importsheet: Starting transaction"); int i, N; for (i = 0, N = s.nEntries(); i < N; i++) { try { CueSheetEntry e = s.entry(i); string file = e.file(); string uuid = Regex.Replace(e.id(), "\\s", "_"); string ext = ".mp3"; string uid = Guid.NewGuid().ToString(); string u1 = uid.Substring(0, 1); string u2 = uid.Substring(0, 2); string dir = basedir + "/.banshee/" + u1; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } dir += "/" + u2; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } uuid = dir + "/" + uuid + ext; UnixFileInfo f = new UnixFileInfo(file); if (File.Exists(uuid)) { File.Delete(uuid); } //f.CreateLink (uuid); f.CreateSymbolicLink(uuid); DatabaseTrackInfo trk = import_manager.ImportTrack(uuid); //File.Delete (uuid); /*if (trk==null) { * Hyena.Log.Warning ("track = null (file="+e.file ()+")"); * if (stk.Count>0) { trk=stk.Pop (); } * }*/ if (trk == null) { Hyena.Log.Error("track = null (file=" + e.file() + ")"); } else { Hyena.Log.Information("track!=null (file=" + e.file() + ")"); //MySource.DbConnection.BeginTransaction(); trk.PartOfCue = 1; trk.CueAudioFile = e.file(); trk.AlbumTitle = s.title(); //trk.Album=s.title (); trk.AlbumArtist = s.performer(); trk.Composer = (e.Composer == "") ? s.composer() : e.Composer; //trk.ArtworkId=s.getArtId (); //trk.Artist= trk.ArtistName = (e.performer() == "") ? s.performer() : e.performer(); trk.TrackTitle = e.title(); trk.TrackNumber = i + 1; trk.Genre = s.genre(); trk.BeginOffset = e.BeginOffset; trk.EndOffset = e.EndOffset; //trk.Uri=trk.CueAudioUri; //trk.MediaAttributes = TrackMediaAttributes.ExternalResource; //trk.PrimarySource = ServiceManager.SourceManager.MusicLibrary; trk.Save(); //MySource.DbConnection.CommitTransaction(); } } catch (Exception ex) { Hyena.Log.Error(ex.ToString()); } } import_manager.NotifyAllSources(); }
public override async Task <string?> RunUpdateAsync( string?currentVersion, string binPath, CancellationToken cancel = default) { try { _logger.LogTrace("Updating..."); var buildRef = await GetLastSuccessfulBuildAsync(cancel); if (buildRef == null) { _logger.LogTrace("No last build?"); return(null); } if (buildRef.Number.ToString(CultureInfo.InvariantCulture) == currentVersion) { _logger.LogTrace("Update not necessary!"); return(null); } _logger.LogTrace("New version is {newVersion} from {oldVersion}", buildRef.Number, currentVersion ?? "<none>"); var downloadRootUri = new Uri($"{_baseUrl}/job/{_jobName}/{buildRef.Number}/artifact/release/"); // Create temporary file to download binary into (not doing this in memory). await using var tempFile = File.Open(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite); // Download URI for server binary. var serverDownload = new Uri(downloadRootUri, $"SS14.Server_{GetHostPlatformName()}_{GetHostArchitectureName()}.zip"); _logger.LogTrace("Downloading server binary from {download} to {tempFile}", serverDownload, tempFile.Name); // Download to file... var resp = await _httpClient.GetAsync(serverDownload, cancel); await resp.Content.CopyToAsync(tempFile, cancel); _logger.LogTrace("Deleting old bin directory ({binPath})", binPath); if (Directory.Exists(binPath)) { Directory.Delete(binPath, true); } Directory.CreateDirectory(binPath); _logger.LogTrace("Extracting zip file"); // Reset file position so we can extract. tempFile.Seek(0, SeekOrigin.Begin); // Actually extract. using var archive = new ZipArchive(tempFile, ZipArchiveMode.Read); archive.ExtractToDirectory(binPath); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // chmod +x Robust.Server var rsPath = Path.Combine(binPath, "Robust.Server"); if (File.Exists(rsPath)) { var f = new UnixFileInfo(rsPath); f.FileAccessPermissions |= FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; } } return(buildRef.Number.ToString(CultureInfo.InvariantCulture)); } catch (Exception e) { _logger.LogError(e, "Failed to run update!"); return(null); } }
private void OnProcessExited(object sender, EventArgs eventArgs) { Interface.Oxide.NextTick(() => { OnCompilerFailed($"compiler version {CompilerVersion} was closed unexpectedly"); if (Environment.OSVersion.Platform == PlatformID.Unix) { string envPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH"); string libraryPath = Path.Combine(Interface.Oxide.ExtensionDirectory, IntPtr.Size == 8 ? "x64" : "x86"); if (string.IsNullOrEmpty(envPath) || !envPath.Contains(libraryPath)) { Interface.Oxide.LogWarning($"LD_LIBRARY_PATH does not container path to compiler dependencies: {libraryPath}"); } else { Interface.Oxide.LogWarning("User running server may not have the proper permissions or install is missing files"); Interface.Oxide.LogWarning($"User running server: {Environment.UserName}"); UnixFileInfo compilerFileInfo = new UnixFileInfo(BinaryPath); Interface.Oxide.LogWarning($"Compiler under user/group: {compilerFileInfo.OwnerUser}/{compilerFileInfo.OwnerGroup}"); string depPath = Path.Combine(Interface.Oxide.ExtensionDirectory, IntPtr.Size == 8 ? "x64" : "x86"); string[] depFiles = { "libmonoboehm-2.0.so.1", "libMonoPosixHelper.so" }; foreach (string file in depFiles) { string filePath = Path.Combine(depPath, file); if (!File.Exists(filePath)) { Interface.Oxide.LogWarning($"{filePath} is missing"); } } } } else { string envPath = Environment.GetEnvironmentVariable("PATH"); string libraryPath = Path.Combine(Interface.Oxide.ExtensionDirectory, "x86"); if (string.IsNullOrEmpty(envPath) || !envPath.Contains(libraryPath)) { Interface.Oxide.LogWarning($"PATH does not container path to compiler dependencies: {libraryPath}"); } else { Interface.Oxide.LogWarning("Compiler may have been closed by interference from security software or install is missing files"); string depPath = Path.Combine(Interface.Oxide.ExtensionDirectory, "x86"); string[] depFiles = { "mono-2.0.dll", "msvcp140.dll", "msvcr120.dll" }; foreach (string file in depFiles) { string filePath = Path.Combine(depPath, file); if (!File.Exists(filePath)) { Interface.Oxide.LogWarning($"{filePath} is missing"); } } } } Shutdown(); }); }
public static void Process(string inputFile, string outputFolder, IDictionary <string, string> opts) { if (!File.Exists(inputFile) && !Directory.Exists(inputFile)) { throw new ArgumentException("Input file does not exist: " + inputFile); } if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } inputFile = Path.GetFullPath(inputFile); outputFolder = Path.GetFullPath(outputFolder); var extension = Path.GetExtension(inputFile).ToLower(); var baseName = Path.GetFileNameWithoutExtension(inputFile); Type type; _importers.TryGetValue(extension, out type); if (type == null) { var attr = File.GetAttributes(inputFile); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { Console.WriteLine("Unrecognized folder extension " + Path.GetExtension(inputFile) + ", skipping."); return; } Console.WriteLine("No custom importer for {0}, copying as blob.", extension); string outputFile = Path.Combine(outputFolder, baseName + extension); if (File.Exists(outputFile) && File.GetLastWriteTime(outputFile) > File.GetLastWriteTime(inputFile)) { return; } if (opts.ContainsKey("Key") && opts.ContainsKey("IV")) { var key = Convert.FromBase64String(opts["Key"]); var iv = Convert.FromBase64String(opts["IV"]); var rm = new RijndaelManaged(); using (var oStream = new CryptoStream(new FileStream(outputFile, FileMode.Create, FileAccess.Write), rm.CreateEncryptor(key, iv), CryptoStreamMode.Write)) { using (var iStream = File.OpenRead(inputFile)) { iStream.CopyTo(oStream); } } } else { File.Copy(inputFile, outputFile, true); var ufi = new UnixFileInfo(outputFile); ufi.FileAccessPermissions |= FileAccessPermissions.UserWrite; } } else { var attr = (ContentTypeAttribute)Attribute.GetCustomAttribute(type, typeof(ContentTypeAttribute)); var importer = (ContentImporter)Activator.CreateInstance(type); foreach (var kvp in opts) { if (kvp.Key == "Key" || kvp.Key == "IV") { continue; } var prop = type.GetProperty(kvp.Key, BindingFlags.IgnoreCase | BindingFlags.Public); if (prop == null) { throw new ArgumentException("No such property found on importer: " + kvp.Key); } prop.SetValue(importer, Convert.ChangeType(kvp.Value, prop.PropertyType), null); } string outputFile = Path.Combine(outputFolder, baseName + (attr.OutExtension == ".*" ? extension : attr.OutExtension)); if (File.Exists(outputFile) && File.GetLastWriteTime(outputFile) > File.GetLastWriteTime(inputFile)) { return; } var oldWorkingDir = Environment.CurrentDirectory; using (FileStream ofStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) { Stream oStream = ofStream; if (opts.ContainsKey("Key") && opts.ContainsKey("IV")) { var key = Convert.FromBase64String(opts["Key"]); var iv = Convert.FromBase64String(opts["IV"]); var rm = new RijndaelManaged(); oStream = new CryptoStream(ofStream, rm.CreateEncryptor(key, iv), CryptoStreamMode.Write); } if (Directory.Exists(inputFile)) { Environment.CurrentDirectory = inputFile; importer.Import(inputFile, oStream); } else { using (FileStream iStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read)) { var dir = Path.GetDirectoryName(inputFile); if (dir != string.Empty) { Environment.CurrentDirectory = Path.GetDirectoryName(inputFile); } importer.Import(iStream, oStream, Path.GetFileName(inputFile)); } } if (oStream is CryptoStream) { ((CryptoStream)oStream).FlushFinalBlock(); } } Environment.CurrentDirectory = oldWorkingDir; } }
public static bool Setup() { if (Connection == null) { Connection = new SqliteConnection($"Filename=" + _SqliteFilename); Connection.Open(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var unixFileInfo = new UnixFileInfo(_SqliteFilename); // set file permission to 666 unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupWrite | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherWrite; } using (var cmd = new SqliteCommand(SQL_CREATE_RUNS, DatabaseManager.Connection, DatabaseManager.Transaction)) { cmd.ExecuteNonQuery(); cmd.CommandText = PRAGMAS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_ROW_KEY_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_TYPE_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_KEY_IDENTITY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_RESULTS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_LEVEL_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_IDENTITY_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_FILE_MONITORED; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_PERSISTED_SETTINGS; cmd.ExecuteNonQuery(); cmd.CommandText = SQL_CREATE_DEFAULT_SETTINGS; cmd.Parameters.AddWithValue("@schema_version", SCHEMA_VERSION); FirstRun &= cmd.ExecuteNonQuery() != 0; } Commit(); return(true); } return(false); }