public string GetRealPath(string path) { do { var link = UnixPath.TryReadLink(path); if (link == null) { var errno = Stdlib.GetLastError(); if (errno != Errno.EINVAL) { _logger.Trace("Checking path {0} for symlink returned error {1}, assuming it's not a symlink.", path, errno); } return(path); } if (UnixPath.IsPathRooted(link)) { path = link; } else { path = UnixPath.GetDirectoryName(path) + UnixPath.DirectorySeparatorChar + link; path = UnixPath.GetCanonicalPath(path); } } while (true); }
public string GetCompleteRealPath(string path) { if (path == null) { return(null); } try { string[] dirs; int lastIndex; GetPathComponents(path, out dirs, out lastIndex); var realPath = new StringBuilder(); if (dirs.Length > 0) { var dir = UnixPath.IsPathRooted(path) ? "/" : ""; dir += dirs[0]; realPath.Append(GetRealPath(dir)); } for (var i = 1; i < lastIndex; ++i) { realPath.Append("/").Append(dirs[i]); var realSubPath = GetRealPath(realPath.ToString()); realPath.Remove(0, realPath.Length); realPath.Append(realSubPath); } return(realPath.ToString()); } catch (Exception ex) { _logger.Debug(ex, string.Format("Failed to check for symlinks in the path {0}", path)); return(path); } }
public ActFileTransferEditPage(Act act) { InitializeComponent(); this.mAct = (ActFileTransfer)act; GingerCore.General.FillComboFromEnumObj(FileTransferActionComboBox, mAct.FileTransferAction); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(FileTransferActionComboBox, ComboBox.TextProperty, mAct, "FileTransferAction"); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(PCPath, TextBox.TextProperty, mAct, ActFileTransfer.Fields.PCPath); PCPath.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.PCPath), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(UnixPath, TextBox.TextProperty, mAct, ActFileTransfer.Fields.UnixPath); UnixPath.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.UnixPath), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(UserName, TextBox.TextProperty, mAct, ActFileTransfer.Fields.UserName); UserName.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.UserName), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(Password, TextBox.TextProperty, mAct, ActFileTransfer.Fields.Password); Password.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.Password), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(PrivateKey, TextBox.TextProperty, mAct, ActFileTransfer.Fields.PrivateKey); PrivateKey.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.PrivateKey), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(KeyPassPhrase, TextBox.TextProperty, mAct, ActFileTransfer.Fields.PrivateKeyPassPhrase); KeyPassPhrase.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.PrivateKeyPassPhrase), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(Port, TextBox.TextProperty, mAct, ActFileTransfer.Fields.Port); Port.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.Port), ActInputValue.Fields.Value); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(Host, TextBox.TextProperty, mAct, ActFileTransfer.Fields.Host); Host.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(ActFileTransfer.Fields.Host), ActInputValue.Fields.Value); }
protected override void CopyFileInternal(string source, string destination, bool overwrite) { var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source); if (sourceInfo.IsSymbolicLink) { var isSameDir = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination); var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo; var symlinkPath = symlinkInfo.ContentsPath; var newFile = new UnixSymbolicLinkInfo(destination); if (FileExists(destination) && overwrite) { DeleteFile(destination); } if (isSameDir) { // We're in the same dir, so we can preserve relative symlinks. newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath); } else { var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath); newFile.CreateSymbolicLinkTo(fullPath); } } else { base.CopyFileInternal(source, destination, overwrite); } }
public void readlink_byte() { foreach (string s in Targets) { string link = UnixPath.Combine(TempFolder, "link"); CreateLink(s); string target = null; byte[] buf = new byte[256]; do { long r = Syscall.readlink(link, buf); if (r < 0) { UnixMarshal.ThrowExceptionForLastError(); } Assert.GreaterOrEqual(buf.Length, r); if (r == buf.Length) { buf = new byte[checked (buf.Length * 2)]; } else { target = UnixEncoding.Instance.GetString(buf, 0, checked ((int)r)); } } while (target == null); Assert.AreEqual(s, target); } }
public static VirtualEntry UnixHandler(string path, string rest) { Stat stat; int r; do { r = Syscall.lstat(path, out stat); } while (r == -1 && Stdlib.GetLastError() == Errno.EINTR); if (r == -1) { return(null); } string parent = UnixPath.GetDirectoryName(path); string name = UnixPath.GetFileName(path); if ((stat.st_mode & FilePermissions.S_IFMT) == FilePermissions.S_IFDIR) { return(new UnixDirectoryEntry(globalMountPoint, parent, name)); } else { return(new UnixFileEntry(globalMountPoint, parent, name)); } }
public void readlink_char() { foreach (string s in Targets) { string link = UnixPath.Combine(TempFolder, "link"); CreateLink(s); var sb = new StringBuilder(256); do { int oldCapacity = sb.Capacity; int r = Syscall.readlink(link, sb); Assert.AreEqual(oldCapacity, sb.Capacity); if (r < 0) { UnixMarshal.ThrowExceptionForLastError(); } Assert.AreEqual(r, sb.Length); Assert.GreaterOrEqual(sb.Capacity, r); if (r == sb.Capacity) { checked { sb.Capacity *= 2; } } else { break; } } while (true); var target = sb.ToString(); Assert.AreEqual(s, target); } }
public void Combine() { string path, expected; string current = UnixDirectoryInfo.GetCurrentDirectory(); path = UnixPath.Combine("/etc", "init.d"); Assert.AreEqual("/etc/init.d", path); path = UnixPath.Combine("one", ""); Assert.AreEqual("one", path); path = UnixPath.Combine("", "one"); Assert.AreEqual("one", path); path = UnixPath.Combine(current, "one"); expected = current + DSC + "one"; Assert.AreEqual(expected, path); path = UnixPath.Combine("one", current); Assert.AreEqual(current, path); path = UnixPath.Combine(current, expected); Assert.AreEqual(expected, path); path = DSC + "one"; path = UnixPath.Combine(path, "two" + DSC); expected = DSC + "one" + DSC + "two" + DSC; Assert.AreEqual(expected, path); path = "one" + DSC; path = UnixPath.Combine(path, DSC + "two"); expected = DSC + "two"; Assert.AreEqual(expected, path); path = "one" + DSC; path = UnixPath.Combine(path, "two" + DSC); expected = "one" + DSC + "two" + DSC; Assert.AreEqual(expected, path); path = UnixPath.Combine("/a", "b", "c", "/d", "e"); expected = "/d/e"; Assert.AreEqual(expected, path); try { path = UnixPath.Combine("one", null); Assert.Fail("Combine Fail #01"); } catch (Exception e) { Assert.AreEqual(typeof(ArgumentNullException), e.GetType()); } try { path = UnixPath.Combine(null, "one"); Assert.Fail("Combine Fail #02"); } catch (Exception e) { Assert.AreEqual(typeof(ArgumentNullException), e.GetType()); } }
/// <inheritdoc /> public Task <IUnixDirectoryEntry> CreateDirectoryAsync( IUnixDirectoryEntry targetDirectory, string directoryName, CancellationToken cancellationToken) { var targetEntry = (UnixDirectoryEntry)targetDirectory; var newDirectoryName = UnixPath.Combine(targetEntry.Info.FullName, directoryName); var newDirectoryInfo = new UnixDirectoryInfo(newDirectoryName); newDirectoryInfo.Create(); return(Task.FromResult((IUnixDirectoryEntry)CreateEntry(targetEntry, newDirectoryInfo))); }
public void TryReadLink() { foreach (string s in Targets) { string link = UnixPath.Combine(TempFolder, "link"); CreateLink(s); var target = UnixPath.TryReadLink(link); Assert.AreEqual(s, target); } }
void CreateLink(string s) { string link = UnixPath.Combine(TempFolder, "link"); //File.Delete (link); // Fails for long link target paths if (Syscall.unlink(link) < 0 && Stdlib.GetLastError() != Errno.ENOENT) { UnixMarshal.ThrowExceptionForLastError(); } if (Syscall.symlink(s, link) < 0) { UnixMarshal.ThrowExceptionForLastError(); } }
public void TryReadLinkAt() { if (!HaveReadlinkAt) { return; } foreach (string s in Targets) { CreateLink(s); var target = UnixPath.TryReadLinkAt(TempFD, "link"); Assert.AreEqual(s, target); } }
public void ReadLinkAt() { if (!HaveReadlinkAt) { Assert.Ignore("No ReadlinkAt."); } foreach (string s in Targets) { CreateLink(s); var target = UnixPath.ReadLinkAt(TempFD, "link"); Assert.AreEqual(s, target); } }
/// <inheritdoc /> public async Task <IBackgroundTransfer> CreateAsync( IUnixDirectoryEntry targetDirectory, string fileName, Stream data, CancellationToken cancellationToken) { var targetInfo = ((UnixDirectoryEntry)targetDirectory).Info; var fileInfo = new UnixFileInfo(UnixPath.Combine(targetInfo.FullName, fileName)); var stream = fileInfo.Open(FileMode.CreateNew, FileAccess.Write, FilePermissions.DEFFILEMODE); /* Must be ConfigureAwait(true) to stay in the same synchronization context. */ await data.CopyToAsync(stream, 81920, cancellationToken) .ConfigureAwait(true); return(null); }
internal AdbEntry(AdbDevice device, FileStatistics fileStatistics, string path) { this.device = device; this.fileStatistics = fileStatistics; this.path = path == null ? fileStatistics.Path : UnixPath.Combine(path, fileStatistics.Path); if (fileStatistics.FileMode.HasFlag(UnixFileMode.SymbolicLink)) { string str = device.ExcecuteCommandResult($"ls -l {this.path}"); Match match = Regex.Match(str, @".*->(?<link>.+)"); if (match.Success) { this.link = match.Groups["link"].Value.Trim(); } } }
protected override void MoveFileInternal(string source, string destination) { var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source); if (sourceInfo.IsSymbolicLink) { var isSameDir = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination); var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo; var symlinkPath = symlinkInfo.ContentsPath; var newFile = new UnixSymbolicLinkInfo(destination); if (isSameDir) { // We're in the same dir, so we can preserve relative symlinks. newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath); } else { var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath); newFile.CreateSymbolicLinkTo(fullPath); } try { // Finally remove the original symlink. symlinkInfo.Delete(); } catch { // Removing symlink failed, so rollback the new link and throw. newFile.Delete(); throw; } } else if ((PlatformInfo.Platform == PlatformType.Mono && PlatformInfo.GetVersion() >= new Version(6, 0)) || PlatformInfo.Platform == PlatformType.NetCore) { TransferFilePatched(source, destination, false, true); } else { base.MoveFileInternal(source, destination); } }
private bool TryFollowFirstSymbolicLink(ref string path) { string[] dirs; int lastIndex; GetPathComponents(path, out dirs, out lastIndex); if (lastIndex == 0) { return(false); } var realPath = ""; for (var i = 0; i < lastIndex; ++i) { if (i != 0 || UnixPath.IsPathRooted(path)) { realPath = string.Concat(realPath, UnixPath.DirectorySeparatorChar, dirs[i]); } else { realPath = string.Concat(realPath, dirs[i]); } var pathValid = TryFollowSymbolicLink(ref realPath, out var wasSymLink); if (!pathValid || wasSymLink) { // If the path does not exist, or it was a symlink then we need to concat the remaining dir components and start over (or return) var count = lastIndex - i - 1; if (count > 0) { realPath = string.Concat(realPath, UnixPath.DirectorySeparatorChar, string.Join(UnixPath.DirectorySeparatorChar.ToString(), dirs, i + 1, lastIndex - i - 1)); } path = realPath; return(pathValid); } } return(false); }
public void ReadlinkMultiByteChar() { string link = UnixPath.Combine(TempFolder, "link"); CreateLink("á"); var sb = new StringBuilder(2); int res = Syscall.readlink(link, sb); if (res < 0) { UnixMarshal.ThrowExceptionForLastError(); } Assert.AreEqual(res, 2); Assert.AreEqual(sb.Length, 2); Assert.AreEqual(sb.Capacity, 2); Assert.AreEqual(sb.ToString(), "á\u0000"); }
/// <inheritdoc/> public IReadOnlyCollection <string> GetVolumes() { if (!Directory.Exists("/sys")) { throw new NotSupportedException("sysfs is not available."); } List <string> drives = new List <string>(); foreach (var dev in Directory.GetDirectories("/sys/block")) { string ueventPath = Path.Combine(dev, "device/uevent"); if (!File.Exists(ueventPath)) { continue; } string[] uevent = File.ReadAllLines(ueventPath); foreach (var line in uevent) { bool doAdd = false; // Detect USB SCSI device (e.g. card reader) if (line == "DRIVER=sd") { string realPath = UnixPath.GetRealPath(dev); if (realPath.Contains("/usb")) { doAdd = true; } } // Detect MMC device (e.g. laptop SD card reader) else if (line == "DRIVER=mmcblk") { doAdd = true; } if (doAdd) { drives.Add(Path.Combine("/dev", Path.GetFileName(dev))); break; } } } return(drives); }
private bool TryFollowSymbolicLink(ref string path, out bool wasSymLink) { if (!UnixFileSystemInfo.TryGetFileSystemEntry(path, out var fsentry) || !fsentry.Exists) { wasSymLink = false; return(false); } if (!fsentry.IsSymbolicLink) { wasSymLink = false; return(true); } var link = UnixPath.TryReadLink(path); if (link == null) { var errno = Stdlib.GetLastError(); if (errno != Errno.EINVAL) { _logger.Trace("Checking path {0} for symlink returned error {1}, assuming it's not a symlink.", path, errno); } wasSymLink = true; return(false); } else { if (UnixPath.IsPathRooted(link)) { path = link; } else { path = UnixPath.GetDirectoryName(path) + UnixPath.DirectorySeparatorChar + link; path = UnixPath.GetCanonicalPath(path); } wasSymLink = true; return(true); } }
public ActTuxedoEditPage(Act act) { InitializeComponent(); this.mAct = (ActTuxedo)act; // Bind Controls App.ObjFieldBinding(PCPath, TextBox.TextProperty, mAct.PCPath, ActInputValue.Fields.Value); App.ObjFieldBinding(PreComamndTextBox, TextBox.TextProperty, mAct.PreCommand, ActInputValue.Fields.Value); UnixPath.Init(Context.GetAsContext(mAct.Context), mAct.UnixPath); HostUCVE.Init(Context.GetAsContext(mAct.Context), mAct.Host); Port.Init(Context.GetAsContext(mAct.Context), mAct.Port); UserName.Init(Context.GetAsContext(mAct.Context), mAct.UserName); Password.Init(Context.GetAsContext(mAct.Context), mAct.Password); PrivateKey.Init(Context.GetAsContext(mAct.Context), mAct.PrivateKey); KeyPassPhrase.Init(Context.GetAsContext(mAct.Context), mAct.PrivateKeyPassPhrase); SetGridView(); }
public static string ReadLink(string symLinkPath, /* see man readlink */ bool canonicalize_existing) { if (!canonicalize_existing) { return(ReadLink(symLinkPath)); } // throws FileNotFoundException if a path component does not exsist, // including the last one. string path = UnixPath.GetCompleteRealPath(symLinkPath); string tmp; while (path != (tmp = UnixPath.GetCompleteRealPath(path))) { path = tmp; } return(path); }
protected override void CopyFileInternal(string source, string destination, bool overwrite) { var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source); if (sourceInfo.IsSymbolicLink) { var isSameDir = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination); var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo; var symlinkPath = symlinkInfo.ContentsPath; var newFile = new UnixSymbolicLinkInfo(destination); if (FileExists(destination) && overwrite) { DeleteFile(destination); } if (isSameDir) { // We're in the same dir, so we can preserve relative symlinks. newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath); } else { var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath); newFile.CreateSymbolicLinkTo(fullPath); } } else if (((PlatformInfo.Platform == PlatformType.Mono && PlatformInfo.GetVersion() >= new Version(6, 0)) || PlatformInfo.Platform == PlatformType.NetCore) && (!FileExists(destination) || overwrite)) { TransferFilePatched(source, destination, overwrite, false); } else { base.CopyFileInternal(source, destination, overwrite); } }
/// <inheritdoc /> public Task <IUnixFileSystemEntry> MoveAsync( IUnixDirectoryEntry parent, IUnixFileSystemEntry source, IUnixDirectoryEntry target, string fileName, CancellationToken cancellationToken) { var sourceInfo = ((UnixFileSystemEntry)source).GenericInfo; var targetEntry = (UnixDirectoryEntry)target; var targetInfo = targetEntry.Info; var sourceEntryName = sourceInfo.FullName; var targetEntryName = UnixPath.Combine(targetInfo.FullName, fileName); if (Stdlib.rename(sourceEntryName, targetEntryName) == -1) { throw new InvalidOperationException("The entry couldn't be moved."); } var targetEntryInfo = UnixFileSystemInfo.GetFileSystemEntry(targetEntryName); return(Task.FromResult(CreateEntry(targetEntry, targetEntryInfo))); }
public void CreateLink(string linkName, string linkPath) { string path = UnixPath.Combine(linkName, linkPath); this.device.ExcecuteCommand($"ln -s {linkPath} {path}"); }
string GetRealPath(string path) { path = UnixPath.GetFullPath(path); return(UnixPath.GetCompleteRealPath(path)); }
static void Main(string[] args) { Console.WriteLine("Usage: Ntrip.exe comport"); Console.WriteLine("Usage: Ntrip.exe comport lat lng alt"); Console.CancelKeyPress += Console_CancelKeyPress; AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { stop = true; Thread.Sleep(1000); }; var tcp = TcpListener.Create(2101); Console.WriteLine("Listerning on 2101"); tcp.Start(); tcp.BeginAcceptTcpClient(processclient, tcp); var ubx = new Ubx(); var rtcm = new rtcm3(); var can = new UAVCAN.uavcan(); Stream file = null; DateTime filetime = DateTime.MinValue; SerialPort port = null; everyminute = DateTime.Now.Minute; Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); // setup allocator can.SourceNode = 127; can.SetupDynamicNodeAllocator(); // feed the rtcm data into the rtcm parser if we get a can message can.MessageReceived += (frame, msg, id) => { if (frame.MsgTypeID == (ushort)uavcan.UAVCAN_EQUIPMENT_GNSS_RTCMSTREAM_DT_ID) { var rtcmcan = (uavcan.uavcan_equipment_gnss_RTCMStream)msg; for (int a = 0; a < rtcmcan.data_len; a++) { int seenmsg = -1; if ((seenmsg = rtcm.Read(rtcmcan.data[a])) > 0) { Console.WriteLine("CANRTCM" + seenmsg); gotRTCMData?.Invoke(rtcm.packet, rtcm.length); file.Write(rtcm.packet, 0, rtcm.length); } } } }; while (!stop) { try { if (port == null || !port.IsOpen) { var comport = args[0]; if (comport.Contains("/dev/")) { comport = UnixPath.GetRealPath(comport); } Console.WriteLine("Port: " + comport); port = new SerialPort(comport, 115200); port.Open(); ubx.SetupM8P(port, true, false); if (args.Length == 4) { ubx.SetupBasePos(port, new PointLatLngAlt(double.Parse(args[1]), double.Parse(args[2]), double.Parse(args[3])), 60, 2); } else { ubx.SetupBasePos(port, PointLatLngAlt.Zero, 60, 2); } } if (file == null || !file.CanWrite || DateTime.UtcNow.Day != filetime.Day) { if (file != null) { file.Close(); } string fn = ""; int no = 0; while (File.Exists((fn = DateTime.UtcNow.ToString("yyyy-MM-dd") + "-" + no + ".rtcm.Z"))) { no++; } file = new GZipStream(new BufferedStream(new FileStream(fn, FileMode.OpenOrCreate)), CompressionMode.Compress); filetime = DateTime.UtcNow; } var btr = port.BytesToRead; if (btr > 0) { totalread += btr; var buffer = new byte[btr]; btr = port.Read(buffer, 0, btr); foreach (byte by in buffer) { btr--; if (ubx.Read((byte)by) > 0) { rtcm.resetParser(); //Console.WriteLine(DateTime.Now + " new ubx message"); } if (by >= 0 && rtcm.Read((byte)by) > 0) { ubx.resetParser(); //Console.WriteLine(DateTime.Now + " new rtcm message"); gotRTCMData?.Invoke(rtcm.packet, rtcm.length); file.Write(rtcm.packet, 0, rtcm.length); } if ((by >= 0 && can.Read(by) > 0))// can_rtcm { ubx.resetParser(); } } } if (DateTime.Now.Minute != everyminute) { Console.WriteLine("{0} bps", totalread / 60); if (totalread == 0) { try { port.Close(); port = null; } catch (Exception ex) { port = null; } } totalread = 0; everyminute = DateTime.Now.Minute; } } catch (UnauthorizedAccessException ex) { Console.WriteLine(ex); Thread.Sleep(5000); } catch (IOException ex) { Console.WriteLine(ex); Thread.Sleep(1000); } catch (Exception ex) { Console.WriteLine(ex); } Thread.Sleep(10); } if (file != null) { file.Close(); } }
public string GetWorkingDirectory() { return(UnixPath.ReadLink("/proc/" + pid + "/cwd")); }
public void CreateFolder(string folderName) { string path = UnixPath.Combine(this.FullName, folderName); this.device.ExcecuteCommand($"mkdir -p \"{path}\""); }