Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,123 @@
//
// Mono.Unix.AbstractUnixEndPoint: EndPoint derived class for AF_UNIX family sockets.
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Alp Toker (alp@atoker.com)
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// (C) 2006 Alp Toker
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Mono.Unix
{
[Serializable]
public class AbstractUnixEndPoint : EndPoint
{
string path;
public AbstractUnixEndPoint (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path == "")
throw new ArgumentException ("Cannot be empty.", "path");
this.path = path;
}
public string Path {
get {
return(path);
}
set {
path=value;
}
}
public override AddressFamily AddressFamily {
get { return AddressFamily.Unix; }
}
public override EndPoint Create (SocketAddress socketAddress)
{
/*
* Should also check this
*
int addr = (int) AddressFamily.Unix;
if (socketAddress [0] != (addr & 0xFF))
throw new ArgumentException ("socketAddress is not a unix socket address.");
if (socketAddress [1] != ((addr & 0xFF00) >> 8))
throw new ArgumentException ("socketAddress is not a unix socket address.");
*/
byte [] bytes = new byte [socketAddress.Size - 2 - 1];
for (int i = 0; i < bytes.Length; i++) {
bytes [i] = socketAddress [2 + 1 + i];
}
string name = Encoding.Default.GetString (bytes);
return new AbstractUnixEndPoint (name);
}
public override SocketAddress Serialize ()
{
byte [] bytes = Encoding.Default.GetBytes (path);
SocketAddress sa = new SocketAddress (AddressFamily, 2 + 1 + bytes.Length);
//NULL prefix denotes the abstract namespace, see unix(7)
//in this case, there is no NULL suffix
sa [2] = 0;
// sa [0] -> family low byte, sa [1] -> family high byte
for (int i = 0; i < bytes.Length; i++)
sa [i + 2 + 1] = bytes [i];
return sa;
}
public override string ToString() {
return(path);
}
public override int GetHashCode ()
{
return path.GetHashCode ();
}
public override bool Equals (object o)
{
AbstractUnixEndPoint other = o as AbstractUnixEndPoint;
if (other == null)
return false;
return (other.path == path);
}
}
}

View File

@@ -0,0 +1,136 @@
//
// Mono.Unix.Catalog.cs: Wrappers for the libintl library.
//
// Authors:
// Edd Dumbill (edd@usefulinc.com)
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004 Edd Dumbill
// (C) 2005-2006 Jonathan Pryor
//
// This file implements the low-level syscall interface to the POSIX
// subsystem.
//
// This file tries to stay close to the low-level API as much as possible
// using enumerations, structures and in a few cases, using existing .NET
// data types.
//
// Implementation notes:
//
// Since the values for the various constants on the API changes
// from system to system (even Linux on different architectures will
// have different values), we define our own set of values, and we
// use a set of C helper routines to map from the constants we define
// to the values of the native OS.
//
// Bitfields are flagged with the [Map] attribute, and a helper program
// generates a set of map_XXXX routines that we can call to convert
// from our value definitions to the value definitions expected by the
// OS.
//
// Methods that require tuning are bound as `internal syscal_NAME' methods
// and then a `NAME' method is exposed.
//
using System;
using System.Runtime.InteropServices;
namespace Mono.Unix {
public class Catalog {
private Catalog () {}
[DllImport("intl", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr bindtextdomain (IntPtr domainname, IntPtr dirname);
[DllImport("intl", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr bind_textdomain_codeset (IntPtr domainname,
IntPtr codeset);
[DllImport("intl", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr textdomain (IntPtr domainname);
public static void Init (String package, String localedir)
{
IntPtr ipackage, ilocaledir, iutf8;
MarshalStrings (package, out ipackage, localedir, out ilocaledir,
"UTF-8", out iutf8);
try {
if (bindtextdomain (ipackage, ilocaledir) == IntPtr.Zero)
throw new UnixIOException (Native.Errno.ENOMEM);
if (bind_textdomain_codeset (ipackage, iutf8) == IntPtr.Zero)
throw new UnixIOException (Native.Errno.ENOMEM);
if (textdomain (ipackage) == IntPtr.Zero)
throw new UnixIOException (Native.Errno.ENOMEM);
}
finally {
UnixMarshal.FreeHeap (ipackage);
UnixMarshal.FreeHeap (ilocaledir);
UnixMarshal.FreeHeap (iutf8);
}
}
private static void MarshalStrings (string s1, out IntPtr p1,
string s2, out IntPtr p2, string s3, out IntPtr p3)
{
p1 = p2 = p3 = IntPtr.Zero;
bool cleanup = true;
try {
p1 = UnixMarshal.StringToHeap (s1);
p2 = UnixMarshal.StringToHeap (s2);
if (s3 != null)
p3 = UnixMarshal.StringToHeap (s3);
cleanup = false;
}
finally {
if (cleanup) {
UnixMarshal.FreeHeap (p1);
UnixMarshal.FreeHeap (p2);
UnixMarshal.FreeHeap (p3);
}
}
}
[DllImport("intl", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr gettext (IntPtr instring);
public static String GetString (String s)
{
IntPtr ints = UnixMarshal.StringToHeap (s);
try {
// gettext(3) returns the input pointer if no translation is found
IntPtr r = gettext (ints);
if (r != ints)
return UnixMarshal.PtrToStringUnix (r);
return s;
}
finally {
UnixMarshal.FreeHeap (ints);
}
}
[DllImport("intl", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr ngettext (IntPtr singular, IntPtr plural, Int32 n);
public static String GetPluralString (String s, String p, Int32 n)
{
IntPtr ints, intp, _ignore;
MarshalStrings (s, out ints, p, out intp, null, out _ignore);
try {
// ngettext(3) returns an input pointer if no translation is found
IntPtr r = ngettext (ints, intp, n);
if (r == ints)
return s;
if (r == intp)
return p;
return UnixMarshal.PtrToStringUnix (r);
}
finally {
UnixMarshal.FreeHeap (ints);
UnixMarshal.FreeHeap (intp);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
//
// Mono.Unix/FileAccessPattern.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
namespace Mono.Unix {
public enum FileAccessPattern {
Normal = Native.PosixFadviseAdvice.POSIX_FADV_NORMAL,
Sequential = Native.PosixFadviseAdvice.POSIX_FADV_SEQUENTIAL,
Random = Native.PosixFadviseAdvice.POSIX_FADV_RANDOM,
NoReuse = Native.PosixFadviseAdvice.POSIX_FADV_NOREUSE,
PreLoad = Native.PosixFadviseAdvice.POSIX_FADV_WILLNEED,
FlushCache = Native.PosixFadviseAdvice.POSIX_FADV_DONTNEED,
}
}

View File

@@ -0,0 +1,53 @@
//
// Mono.Unix/FileAccessPermissions.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
namespace Mono.Unix {
[Flags]
public enum FileAccessPermissions {
UserReadWriteExecute = (int) Native.FilePermissions.S_IRWXU,
UserRead = (int) Native.FilePermissions.S_IRUSR,
UserWrite = (int) Native.FilePermissions.S_IWUSR,
UserExecute = (int) Native.FilePermissions.S_IXUSR,
GroupReadWriteExecute = (int) Native.FilePermissions.S_IRWXG,
GroupRead = (int) Native.FilePermissions.S_IRGRP,
GroupWrite = (int) Native.FilePermissions.S_IWGRP,
GroupExecute = (int) Native.FilePermissions.S_IXGRP,
OtherReadWriteExecute = (int) Native.FilePermissions.S_IRWXO,
OtherRead = (int) Native.FilePermissions.S_IROTH,
OtherWrite = (int) Native.FilePermissions.S_IWOTH,
OtherExecute = (int) Native.FilePermissions.S_IXOTH,
DefaultPermissions = (int) Native.FilePermissions.DEFFILEMODE,
AllPermissions = (int) Native.FilePermissions.ACCESSPERMS,
}
}

View File

@@ -0,0 +1,82 @@
//
// Mono.Unix/FileHandleOperations.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public sealed /* static */ class FileHandleOperations
{
private FileHandleOperations () {}
public static void AdviseFileAccessPattern (int fd, FileAccessPattern pattern, long offset, long len)
{
int r = Native.Syscall.posix_fadvise (fd, offset, len,
(Native.PosixFadviseAdvice) pattern);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static void AdviseFileAccessPattern (int fd, FileAccessPattern pattern)
{
AdviseFileAccessPattern (fd, pattern, 0, 0);
}
public static void AdviseFileAccessPattern (FileStream file, FileAccessPattern pattern, long offset, long len)
{
if (file == null)
throw new ArgumentNullException ("file");
int r = Native.Syscall.posix_fadvise (file.Handle.ToInt32(), offset, len,
(Native.PosixFadviseAdvice) pattern);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static void AdviseFileAccessPattern (FileStream file, FileAccessPattern pattern)
{
AdviseFileAccessPattern (file, pattern, 0, 0);
}
public static void AdviseFileAccessPattern (UnixStream stream, FileAccessPattern pattern, long offset, long len)
{
if (stream == null)
throw new ArgumentNullException ("stream");
int r = Native.Syscall.posix_fadvise (stream.Handle, offset, len,
(Native.PosixFadviseAdvice) pattern);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static void AdviseFileAccessPattern (UnixStream stream, FileAccessPattern pattern)
{
AdviseFileAccessPattern (stream, pattern, 0, 0);
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,41 @@
//
// Mono.Unix/FileSpecialAttributes.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
namespace Mono.Unix {
[Flags]
public enum FileSpecialAttributes {
SetUserId = (int) Native.FilePermissions.S_ISUID,
SetGroupId = (int) Native.FilePermissions.S_ISGID,
Sticky = (int) Native.FilePermissions.S_ISVTX,
}
}

View File

@@ -0,0 +1,44 @@
//
// Mono.Unix/FileTypes.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
namespace Mono.Unix {
public enum FileTypes {
Directory = (int) Native.FilePermissions.S_IFDIR,
CharacterDevice = (int) Native.FilePermissions.S_IFCHR,
BlockDevice = (int) Native.FilePermissions.S_IFBLK,
RegularFile = (int) Native.FilePermissions.S_IFREG,
Fifo = (int) Native.FilePermissions.S_IFIFO,
SymbolicLink = (int) Native.FilePermissions.S_IFLNK,
Socket = (int) Native.FilePermissions.S_IFSOCK,
}
}

View File

@@ -0,0 +1,73 @@
//
// Mono.Unix.PeerCred: Peer credentials class for AF_UNIX sockets
//
// Authors:
// Dick Porter (dick@ximian.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Sockets;
namespace Mono.Unix
{
public class PeerCred
{
/* Make sure this doesn't clash with anything in
* SocketOptionName, and keep it synchronised with the
* runtime
*/
private const int so_peercred=10001;
private Mono.Posix.PeerCredData data;
public PeerCred (Socket sock) {
if (sock.AddressFamily != AddressFamily.Unix) {
throw new ArgumentException ("Only Unix sockets are supported", "sock");
}
data = (Mono.Posix.PeerCredData)
sock.GetSocketOption (SocketOptionLevel.Socket, (SocketOptionName)so_peercred);
}
public int ProcessID {
get {
return(data.pid);
}
}
public int UserID {
get {
return(data.uid);
}
}
public int GroupID {
get {
return(data.gid);
}
}
}
}

View File

@@ -0,0 +1,398 @@
//
// Mono.Unix/StdioFileStream.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2005-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public class StdioFileStream : Stream
{
public static readonly IntPtr InvalidFileStream = IntPtr.Zero;
public static readonly IntPtr StandardInput = Native.Stdlib.stdin;
public static readonly IntPtr StandardOutput = Native.Stdlib.stdout;
public static readonly IntPtr StandardError = Native.Stdlib.stderr;
public StdioFileStream (IntPtr fileStream)
: this (fileStream, true) {}
public StdioFileStream (IntPtr fileStream, bool ownsHandle)
{
InitStream (fileStream, ownsHandle);
}
public StdioFileStream (IntPtr fileStream, FileAccess access)
: this (fileStream, access, true) {}
public StdioFileStream (IntPtr fileStream, FileAccess access, bool ownsHandle)
{
InitStream (fileStream, ownsHandle);
InitCanReadWrite (access);
}
public StdioFileStream (string path)
{
InitStream (Fopen (path, "rb"), true);
}
public StdioFileStream (string path, string mode)
{
InitStream (Fopen (path, mode), true);
}
public StdioFileStream (string path, FileMode mode)
{
InitStream (Fopen (path, ToFopenMode (path, mode)), true);
}
public StdioFileStream (string path, FileAccess access)
{
InitStream (Fopen (path, ToFopenMode (path, access)), true);
InitCanReadWrite (access);
}
public StdioFileStream (string path, FileMode mode, FileAccess access)
{
InitStream (Fopen (path, ToFopenMode (path, mode, access)), true);
InitCanReadWrite (access);
}
private static IntPtr Fopen (string path, string mode)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("path");
if (mode == null)
throw new ArgumentNullException ("mode");
IntPtr f = Native.Stdlib.fopen (path, mode);
if (f == IntPtr.Zero)
throw new DirectoryNotFoundException ("path",
UnixMarshal.CreateExceptionForLastError ());
return f;
}
private void InitStream (IntPtr fileStream, bool ownsHandle)
{
if (InvalidFileStream == fileStream)
throw new ArgumentException (Locale.GetText ("Invalid file stream"), "fileStream");
this.file = fileStream;
this.owner = ownsHandle;
try {
long offset = Native.Stdlib.fseek (file, 0, Native.SeekFlags.SEEK_CUR);
if (offset != -1)
canSeek = true;
Native.Stdlib.fread (IntPtr.Zero, 0, 0, file);
if (Native.Stdlib.ferror (file) == 0)
canRead = true;
Native.Stdlib.fwrite (IntPtr.Zero, 0, 0, file);
if (Native.Stdlib.ferror (file) == 0)
canWrite = true;
Native.Stdlib.clearerr (file);
}
catch (Exception) {
throw new ArgumentException (Locale.GetText ("Invalid file stream"), "fileStream");
}
GC.KeepAlive (this);
}
private void InitCanReadWrite (FileAccess access)
{
canRead = canRead &&
(access == FileAccess.Read || access == FileAccess.ReadWrite);
canWrite = canWrite &&
(access == FileAccess.Write || access == FileAccess.ReadWrite);
}
private static string ToFopenMode (string file, FileMode mode)
{
string cmode = Native.NativeConvert.ToFopenMode (mode);
AssertFileMode (file, mode);
return cmode;
}
private static string ToFopenMode (string file, FileAccess access)
{
return Native.NativeConvert.ToFopenMode (access);
}
private static string ToFopenMode (string file, FileMode mode, FileAccess access)
{
string cmode = Native.NativeConvert.ToFopenMode (mode, access);
bool exists = AssertFileMode (file, mode);
// HACK: for open-or-create & read, mode is "rb", which doesn't create
// files. If the file doesn't exist, we need to use "w+b" to ensure
// file creation.
if (mode == FileMode.OpenOrCreate && access == FileAccess.Read && !exists)
cmode = "w+b";
return cmode;
}
private static bool AssertFileMode (string file, FileMode mode)
{
bool exists = FileExists (file);
if (mode == FileMode.CreateNew && exists)
throw new IOException ("File exists and FileMode.CreateNew specified");
if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists)
throw new FileNotFoundException ("File doesn't exist and FileMode.Open specified", file);
return exists;
}
private static bool FileExists (string file)
{
bool found = false;
IntPtr f = Native.Stdlib.fopen (file, "r");
found = f != IntPtr.Zero;
if (f != IntPtr.Zero)
Native.Stdlib.fclose (f);
return found;
}
private void AssertNotDisposed ()
{
if (file == InvalidFileStream)
throw new ObjectDisposedException ("Invalid File Stream");
GC.KeepAlive (this);
}
public IntPtr Handle {
get {
AssertNotDisposed ();
GC.KeepAlive (this);
return file;
}
}
public override bool CanRead {
get {return canRead;}
}
public override bool CanSeek {
get {return canSeek;}
}
public override bool CanWrite {
get {return canWrite;}
}
public override long Length {
get {
AssertNotDisposed ();
if (!CanSeek)
throw new NotSupportedException ("File Stream doesn't support seeking");
long curPos = Native.Stdlib.ftell (file);
if (curPos == -1)
throw new NotSupportedException ("Unable to obtain current file position");
int r = Native.Stdlib.fseek (file, 0, Native.SeekFlags.SEEK_END);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
long endPos = Native.Stdlib.ftell (file);
if (endPos == -1)
UnixMarshal.ThrowExceptionForLastError ();
r = Native.Stdlib.fseek (file, curPos, Native.SeekFlags.SEEK_SET);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
GC.KeepAlive (this);
return endPos;
}
}
public override long Position {
get {
AssertNotDisposed ();
if (!CanSeek)
throw new NotSupportedException ("The stream does not support seeking");
long pos = Native.Stdlib.ftell (file);
if (pos == -1)
UnixMarshal.ThrowExceptionForLastError ();
GC.KeepAlive (this);
return (long) pos;
}
set {
AssertNotDisposed ();
Seek (value, SeekOrigin.Begin);
}
}
public void SaveFilePosition (Native.FilePosition pos)
{
AssertNotDisposed ();
int r = Native.Stdlib.fgetpos (file, pos);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
GC.KeepAlive (this);
}
public void RestoreFilePosition (Native.FilePosition pos)
{
AssertNotDisposed ();
if (pos == null)
throw new ArgumentNullException ("value");
int r = Native.Stdlib.fsetpos (file, pos);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
GC.KeepAlive (this);
}
public override void Flush ()
{
AssertNotDisposed ();
int r = Native.Stdlib.fflush (file);
if (r != 0)
UnixMarshal.ThrowExceptionForLastError ();
GC.KeepAlive (this);
}
public override unsafe int Read ([In, Out] byte[] buffer, int offset, int count)
{
AssertNotDisposed ();
AssertValidBuffer (buffer, offset, count);
if (!CanRead)
throw new NotSupportedException ("Stream does not support reading");
ulong r = 0;
fixed (byte* buf = &buffer[offset]) {
r = Native.Stdlib.fread (buf, 1, (ulong) count, file);
}
if (r != (ulong) count) {
if (Native.Stdlib.ferror (file) != 0)
throw new IOException ();
}
GC.KeepAlive (this);
return (int) r;
}
private void AssertValidBuffer (byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException ("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
if (offset > buffer.Length)
throw new ArgumentException ("destination offset is beyond array size");
if (offset > (buffer.Length - count))
throw new ArgumentException ("would overrun buffer");
}
public void Rewind ()
{
AssertNotDisposed ();
Native.Stdlib.rewind (file);
GC.KeepAlive (this);
}
public override long Seek (long offset, SeekOrigin origin)
{
AssertNotDisposed ();
if (!CanSeek)
throw new NotSupportedException ("The File Stream does not support seeking");
Native.SeekFlags sf = Native.SeekFlags.SEEK_CUR;
switch (origin) {
case SeekOrigin.Begin: sf = Native.SeekFlags.SEEK_SET; break;
case SeekOrigin.Current: sf = Native.SeekFlags.SEEK_CUR; break;
case SeekOrigin.End: sf = Native.SeekFlags.SEEK_END; break;
default: throw new ArgumentException ("origin");
}
int r = Native.Stdlib.fseek (file, offset, sf);
if (r != 0)
throw new IOException ("Unable to seek",
UnixMarshal.CreateExceptionForLastError ());
long pos = Native.Stdlib.ftell (file);
if (pos == -1)
throw new IOException ("Unable to get current file position",
UnixMarshal.CreateExceptionForLastError ());
GC.KeepAlive (this);
return pos;
}
public override void SetLength (long value)
{
throw new NotSupportedException ("ANSI C doesn't provide a way to truncate a file");
}
public override unsafe void Write (byte[] buffer, int offset, int count)
{
AssertNotDisposed ();
AssertValidBuffer (buffer, offset, count);
if (!CanWrite)
throw new NotSupportedException ("File Stream does not support writing");
ulong r = 0;
fixed (byte* buf = &buffer[offset]) {
r = Native.Stdlib.fwrite (buf, (ulong) 1, (ulong) count, file);
}
if (r != (ulong) count)
UnixMarshal.ThrowExceptionForLastError ();
GC.KeepAlive (this);
}
~StdioFileStream ()
{
Close ();
}
public override void Close ()
{
if (file == InvalidFileStream)
return;
if (owner) {
int r = Native.Stdlib.fclose (file);
if (r != 0)
UnixMarshal.ThrowExceptionForLastError ();
} else
Flush ();
file = InvalidFileStream;
canRead = false;
canSeek = false;
canWrite = false;
GC.SuppressFinalize (this);
GC.KeepAlive (this);
}
private bool canSeek = false;
private bool canRead = false;
private bool canWrite = false;
private bool owner = true;
private IntPtr file = InvalidFileStream;
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,234 @@
//
// UnixListener.cs
//
// Authors:
// Joe Shaw (joeshaw@novell.com)
//
// Copyright (C) 2004-2005 Novell, Inc.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace Mono.Unix {
public class UnixClient : MarshalByRefObject, IDisposable {
NetworkStream stream;
Socket client;
bool disposed;
public UnixClient ()
{
if (client != null) {
client.Close ();
client = null;
}
client = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
}
public UnixClient (string path) : this ()
{
if (path == null)
throw new ArgumentNullException ("ep");
Connect (path);
}
public UnixClient (UnixEndPoint ep) : this ()
{
if (ep == null)
throw new ArgumentNullException ("ep");
Connect (ep);
}
// UnixListener uses this when accepting a connection.
internal UnixClient (Socket sock)
{
Client = sock;
}
#if NET_2_0
public
#else
protected
#endif
Socket Client {
get { return client; }
set {
client = value;
stream = null;
}
}
public PeerCred PeerCredential {
get {
CheckDisposed ();
return new PeerCred (client);
}
}
public LingerOption LingerState {
get {
CheckDisposed ();
return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.Linger);
}
set {
CheckDisposed ();
client.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.Linger, value);
}
}
public int ReceiveBufferSize {
get {
CheckDisposed ();
return (int) client.GetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer);
}
set {
CheckDisposed ();
client.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, value);
}
}
public int ReceiveTimeout {
get {
CheckDisposed ();
return (int) client.GetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set {
CheckDisposed ();
client.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}
public int SendBufferSize {
get {
CheckDisposed ();
return (int) client.GetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.SendBuffer);
}
set {
CheckDisposed ();
client.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.SendBuffer, value);
}
}
public int SendTimeout {
get {
CheckDisposed ();
return (int) client.GetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.SendTimeout);
}
set {
CheckDisposed ();
client.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, value);
}
}
public void Close ()
{
CheckDisposed ();
Dispose ();
}
public void Connect (UnixEndPoint remoteEndPoint)
{
CheckDisposed ();
client.Connect (remoteEndPoint);
stream = new NetworkStream (client, true);
}
public void Connect (string path)
{
CheckDisposed ();
Connect (new UnixEndPoint (path));
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (disposed)
return;
if (disposing) {
// release managed resources
NetworkStream s = stream;
stream = null;
if (s != null) {
// This closes the socket as well, as the NetworkStream
// owns the socket.
s.Close();
s = null;
} else if (client != null){
client.Close ();
}
client = null;
}
disposed = true;
}
public NetworkStream GetStream ()
{
CheckDisposed ();
if (stream == null)
stream = new NetworkStream (client, true);
return stream;
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException (GetType().FullName);
}
~UnixClient ()
{
Dispose (false);
}
}
}

View File

@@ -0,0 +1,250 @@
//
// Mono.Unix/UnixDirectoryInfo.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Mono.Unix;
namespace Mono.Unix {
public sealed class UnixDirectoryInfo : UnixFileSystemInfo
{
public UnixDirectoryInfo (string path)
: base (path)
{
}
internal UnixDirectoryInfo (string path, Native.Stat stat)
: base (path, stat)
{
}
public override string Name {
get {
string r = UnixPath.GetFileName (FullPath);
if (r == null || r.Length == 0)
return FullPath;
return r;
}
}
public UnixDirectoryInfo Parent {
get {
if (FullPath == "/")
return this;
string dirname = UnixPath.GetDirectoryName (FullPath);
if (dirname == "")
throw new InvalidOperationException ("Do not know parent directory for path `" + FullPath + "'");
return new UnixDirectoryInfo (dirname);
}
}
public UnixDirectoryInfo Root {
get {
string root = UnixPath.GetPathRoot (FullPath);
if (root == null)
return null;
return new UnixDirectoryInfo (root);
}
}
[CLSCompliant (false)]
public void Create (Mono.Unix.Native.FilePermissions mode)
{
int r = Mono.Unix.Native.Syscall.mkdir (FullPath, mode);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
base.Refresh ();
}
public void Create (FileAccessPermissions mode)
{
Create ((Native.FilePermissions) mode);
}
public void Create ()
{
Mono.Unix.Native.FilePermissions mode =
Mono.Unix.Native.FilePermissions.ACCESSPERMS;
Create (mode);
}
public override void Delete ()
{
Delete (false);
}
public void Delete (bool recursive)
{
if (recursive) {
foreach (UnixFileSystemInfo e in GetFileSystemEntries ()) {
UnixDirectoryInfo d = e as UnixDirectoryInfo;
if (d != null)
d.Delete (true);
else
e.Delete ();
}
}
int r = Native.Syscall.rmdir (FullPath);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
base.Refresh ();
}
public Native.Dirent[] GetEntries ()
{
IntPtr dirp = Native.Syscall.opendir (FullPath);
if (dirp == IntPtr.Zero)
UnixMarshal.ThrowExceptionForLastError ();
bool complete = false;
try {
Native.Dirent[] entries = GetEntries (dirp);
complete = true;
return entries;
}
finally {
int r = Native.Syscall.closedir (dirp);
// don't throw an exception if an exception is in progress
if (complete)
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
}
private static Native.Dirent[] GetEntries (IntPtr dirp)
{
ArrayList entries = new ArrayList ();
int r;
IntPtr result;
do {
Native.Dirent d = new Native.Dirent ();
r = Native.Syscall.readdir_r (dirp, d, out result);
if (r == 0 && result != IntPtr.Zero)
// don't include current & parent dirs
if (d.d_name != "." && d.d_name != "..")
entries.Add (d);
} while (r == 0 && result != IntPtr.Zero);
if (r != 0)
UnixMarshal.ThrowExceptionForLastErrorIf (r);
return (Native.Dirent[]) entries.ToArray (typeof(Native.Dirent));
}
public Native.Dirent[] GetEntries (Regex regex)
{
IntPtr dirp = Native.Syscall.opendir (FullPath);
if (dirp == IntPtr.Zero)
UnixMarshal.ThrowExceptionForLastError ();
try {
return GetEntries (dirp, regex);
}
finally {
int r = Native.Syscall.closedir (dirp);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
}
private static Native.Dirent[] GetEntries (IntPtr dirp, Regex regex)
{
ArrayList entries = new ArrayList ();
int r;
IntPtr result;
do {
Native.Dirent d = new Native.Dirent ();
r = Native.Syscall.readdir_r (dirp, d, out result);
if (r == 0 && result != IntPtr.Zero && regex.Match (d.d_name).Success) {
// don't include current & parent dirs
if (d.d_name != "." && d.d_name != "..")
entries.Add (d);
}
} while (r == 0 && result != IntPtr.Zero);
if (r != 0)
UnixMarshal.ThrowExceptionForLastError ();
return (Native.Dirent[]) entries.ToArray (typeof(Native.Dirent));
}
public Native.Dirent[] GetEntries (string regex)
{
Regex re = new Regex (regex);
return GetEntries (re);
}
public UnixFileSystemInfo[] GetFileSystemEntries ()
{
Native.Dirent[] dentries = GetEntries ();
return GetFileSystemEntries (dentries);
}
private UnixFileSystemInfo[] GetFileSystemEntries (Native.Dirent[] dentries)
{
UnixFileSystemInfo[] entries = new UnixFileSystemInfo[dentries.Length];
for (int i = 0; i != entries.Length; ++i)
entries [i] = UnixFileSystemInfo.GetFileSystemEntry (
UnixPath.Combine (FullPath, dentries[i].d_name));
return entries;
}
public UnixFileSystemInfo[] GetFileSystemEntries (Regex regex)
{
Native.Dirent[] dentries = GetEntries (regex);
return GetFileSystemEntries (dentries);
}
public UnixFileSystemInfo[] GetFileSystemEntries (string regex)
{
Regex re = new Regex (regex);
return GetFileSystemEntries (re);
}
public static string GetCurrentDirectory ()
{
StringBuilder buf = new StringBuilder (16);
IntPtr r = IntPtr.Zero;
do {
buf.Capacity *= 2;
r = Native.Syscall.getcwd (buf, (ulong) buf.Capacity);
} while (r == IntPtr.Zero && Native.Syscall.GetLastError() == Native.Errno.ERANGE);
if (r == IntPtr.Zero)
UnixMarshal.ThrowExceptionForLastError ();
return buf.ToString ();
}
public static void SetCurrentDirectory (string path)
{
int r = Native.Syscall.chdir (path);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,195 @@
//
// Mono.Unix/UnixDriveInfo.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using Mono.Unix;
namespace Mono.Unix {
public enum UnixDriveType {
Unknown,
NoRootDirectory,
Removable,
Fixed,
Network,
CDRom,
Ram
}
// All methods & properties can throw IOException
public sealed class UnixDriveInfo
{
private Native.Statvfs stat;
private string fstype, mount_point, block_device;
public UnixDriveInfo (string mountPoint)
{
if (mountPoint == null)
throw new ArgumentNullException ("mountPoint");
Native.Fstab fstab = Native.Syscall.getfsfile (mountPoint);
if (fstab != null) {
FromFstab (fstab);
}
else {
this.mount_point = mountPoint;
this.block_device = "";
this.fstype = "Unknown";
}
}
private void FromFstab (Native.Fstab fstab)
{
this.fstype = fstab.fs_vfstype;
this.mount_point = fstab.fs_file;
this.block_device = fstab.fs_spec;
}
public static UnixDriveInfo GetForSpecialFile (string specialFile)
{
if (specialFile == null)
throw new ArgumentNullException ("specialFile");
Native.Fstab f = Native.Syscall.getfsspec (specialFile);
if (f == null)
throw new ArgumentException ("specialFile isn't valid: " + specialFile);
return new UnixDriveInfo (f);
}
private UnixDriveInfo (Native.Fstab fstab)
{
FromFstab (fstab);
}
public long AvailableFreeSpace {
get {Refresh (); return Convert.ToInt64 (stat.f_bavail * stat.f_frsize);}
}
public string DriveFormat {
get {return fstype;}
}
public UnixDriveType DriveType {
get {return UnixDriveType.Unknown;}
}
// this throws no exceptions
public bool IsReady {
get {
bool ready = Refresh (false);
if (mount_point == "/" || !ready)
return ready;
Native.Statvfs parent;
int r = Native.Syscall.statvfs (RootDirectory.Parent.FullName,
out parent);
if (r != 0)
return false;
return parent.f_fsid != stat.f_fsid;
}
}
public string Name {
get {return mount_point;}
}
public UnixDirectoryInfo RootDirectory {
get {return new UnixDirectoryInfo (mount_point);}
}
public long TotalFreeSpace {
get {Refresh (); return (long) (stat.f_bfree * stat.f_frsize);}
}
public long TotalSize {
get {Refresh (); return (long) (stat.f_frsize * stat.f_blocks);}
}
// also throws SecurityException if caller lacks perms
public string VolumeLabel {
get {return block_device;}
// set {}
}
public long MaximumFilenameLength {
get {Refresh (); return Convert.ToInt64 (stat.f_namemax);}
}
public static UnixDriveInfo[] GetDrives ()
{
// TODO: Return any drives mentioned by getmntent(3) once getmntent(3)
// is exported by Syscall.
// throws IOException, UnauthorizedAccessException (no permission)
ArrayList entries = new ArrayList ();
lock (Native.Syscall.fstab_lock) {
int r = Native.Syscall.setfsent ();
if (r != 1)
throw new IOException ("Error calling setfsent(3)", new UnixIOException ());
try {
Native.Fstab fs;
while ((fs = Native.Syscall.getfsent()) != null) {
// avoid virtual entries, such as "swap"
if (fs.fs_file != null && fs.fs_file.StartsWith ("/"))
entries.Add (new UnixDriveInfo (fs));
}
}
finally {
Native.Syscall.endfsent ();
}
}
return (UnixDriveInfo[]) entries.ToArray (typeof(UnixDriveInfo));
}
public override string ToString ()
{
return VolumeLabel;
}
private void Refresh ()
{
Refresh (true);
}
private bool Refresh (bool throwException)
{
int r = Native.Syscall.statvfs (mount_point, out stat);
if (r == -1 && throwException) {
Native.Errno e = Native.Syscall.GetLastError ();
throw new InvalidOperationException (
UnixMarshal.GetErrorDescription (e),
new UnixIOException (e));
}
else if (r == -1)
return false;
return true;
}
}
}
// vim: noexpandtab

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
//
// Mono.Unix.UnixEndPoint: EndPoint derived class for AF_UNIX family sockets.
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Mono.Unix
{
[Serializable]
public class UnixEndPoint : EndPoint
{
string filename;
public UnixEndPoint (string filename)
{
if (filename == null)
throw new ArgumentNullException ("filename");
if (filename == "")
throw new ArgumentException ("Cannot be empty.", "filename");
this.filename = filename;
}
public string Filename {
get {
return(filename);
}
set {
filename=value;
}
}
public override AddressFamily AddressFamily {
get { return AddressFamily.Unix; }
}
public override EndPoint Create (SocketAddress socketAddress)
{
/*
* Should also check this
*
int addr = (int) AddressFamily.Unix;
if (socketAddress [0] != (addr & 0xFF))
throw new ArgumentException ("socketAddress is not a unix socket address.");
if (socketAddress [1] != ((addr & 0xFF00) >> 8))
throw new ArgumentException ("socketAddress is not a unix socket address.");
*/
if (socketAddress.Size == 2) {
// Empty filename.
// Probably from RemoteEndPoint which on linux does not return the file name.
UnixEndPoint uep = new UnixEndPoint ("a");
uep.filename = "";
return uep;
}
byte [] bytes = new byte [socketAddress.Size - 2 - 1];
for (int i = 0; i < bytes.Length; i++) {
bytes [i] = socketAddress [i + 2];
}
string name = Encoding.Default.GetString (bytes);
return new UnixEndPoint (name);
}
public override SocketAddress Serialize ()
{
byte [] bytes = Encoding.Default.GetBytes (filename);
SocketAddress sa = new SocketAddress (AddressFamily, 2 + bytes.Length + 1);
// sa [0] -> family low byte, sa [1] -> family high byte
for (int i = 0; i < bytes.Length; i++)
sa [2 + i] = bytes [i];
//NULL suffix for non-abstract path
sa[2 + bytes.Length] = 0;
return sa;
}
public override string ToString() {
return(filename);
}
public override int GetHashCode ()
{
return filename.GetHashCode ();
}
public override bool Equals (object o)
{
UnixEndPoint other = o as UnixEndPoint;
if (other == null)
return false;
return (other.filename == filename);
}
}
}

View File

@@ -0,0 +1,238 @@
//
// Mono.Unix/UnixEnvironment.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public sealed /* static */ class UnixEnvironment
{
private UnixEnvironment () {}
public static string CurrentDirectory {
get {
return UnixDirectoryInfo.GetCurrentDirectory ();
}
set {
UnixDirectoryInfo.SetCurrentDirectory (value);
}
}
public static string MachineName {
get {
Native.Utsname buf;
if (Native.Syscall.uname (out buf) != 0)
throw UnixMarshal.CreateExceptionForLastError ();
return buf.nodename;
}
set {
int r = Native.Syscall.sethostname (value);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
}
public static string UserName {
get {return UnixUserInfo.GetRealUser ().UserName;}
}
public static UnixGroupInfo RealGroup {
get {return new UnixGroupInfo (RealGroupId);}
// set can't be done as setgid(2) modifies effective gid as well
}
public static long RealGroupId {
get {return Native.Syscall.getgid ();}
// set can't be done as setgid(2) modifies effective gid as well
}
public static UnixUserInfo RealUser {
get {return new UnixUserInfo (RealUserId);}
// set can't be done as setuid(2) modifies effective uid as well
}
public static long RealUserId {
get {return Native.Syscall.getuid ();}
// set can't be done as setuid(2) modifies effective uid as well
}
public static UnixGroupInfo EffectiveGroup {
get {return new UnixGroupInfo (EffectiveGroupId);}
set {EffectiveGroupId = value.GroupId;}
}
public static long EffectiveGroupId {
get {return Native.Syscall.getegid ();}
set {Native.Syscall.setegid (Convert.ToUInt32 (value));}
}
public static UnixUserInfo EffectiveUser {
get {return new UnixUserInfo (EffectiveUserId);}
set {EffectiveUserId = value.UserId;}
}
public static long EffectiveUserId {
get {return Native.Syscall.geteuid ();}
set {Native.Syscall.seteuid (Convert.ToUInt32 (value));}
}
public static string Login {
get {return UnixUserInfo.GetRealUser ().UserName;}
}
[CLSCompliant (false)]
public static long GetConfigurationValue (Native.SysconfName name)
{
long r = Native.Syscall.sysconf (name);
if (r == -1 && Native.Stdlib.GetLastError() != (Native.Errno) 0)
UnixMarshal.ThrowExceptionForLastError ();
return r;
}
[CLSCompliant (false)]
public static string GetConfigurationString (Native.ConfstrName name)
{
ulong len = Native.Syscall.confstr (name, null, 0);
if (len == unchecked ((ulong) (-1)))
UnixMarshal.ThrowExceptionForLastError ();
if (len == 0)
return "";
StringBuilder buf = new StringBuilder ((int) len+1);
len = Native.Syscall.confstr (name, buf, len);
if (len == unchecked ((ulong) (-1)))
UnixMarshal.ThrowExceptionForLastError ();
return buf.ToString ();
}
public static void SetNiceValue (int inc)
{
int r = Native.Syscall.nice (inc);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static int CreateSession ()
{
int s = Native.Syscall.setsid ();
UnixMarshal.ThrowExceptionForLastErrorIf (s);
return s;
}
public static void SetProcessGroup ()
{
int r = Native.Syscall.setpgrp ();
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static int GetProcessGroup ()
{
return Native.Syscall.getpgrp ();
}
public static UnixGroupInfo[] GetSupplementaryGroups ()
{
uint[] ids = _GetSupplementaryGroupIds ();
UnixGroupInfo[] groups = new UnixGroupInfo [ids.Length];
for (int i = 0; i < groups.Length; ++i)
groups [i] = new UnixGroupInfo (ids [i]);
return groups;
}
private static uint[] _GetSupplementaryGroupIds ()
{
int ngroups = Native.Syscall.getgroups (0, new uint[]{});
if (ngroups == -1)
UnixMarshal.ThrowExceptionForLastError ();
uint[] groups = new uint[ngroups];
int r = Native.Syscall.getgroups (groups);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
return groups;
}
public static void SetSupplementaryGroups (UnixGroupInfo[] groups)
{
uint[] list = new uint [groups.Length];
for (int i = 0; i < list.Length; ++i) {
list [i] = Convert.ToUInt32 (groups [i].GroupId);
}
int r = Native.Syscall.setgroups (list);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static long[] GetSupplementaryGroupIds ()
{
uint[] _groups = _GetSupplementaryGroupIds ();
long[] groups = new long [_groups.Length];
for (int i = 0; i < groups.Length; ++i)
groups [i] = _groups [i];
return groups;
}
public static void SetSupplementaryGroupIds (long[] list)
{
uint[] _list = new uint [list.Length];
for (int i = 0; i < _list.Length; ++i)
_list [i] = Convert.ToUInt32 (list [i]);
int r = Native.Syscall.setgroups (_list);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public static int GetParentProcessId ()
{
return Native.Syscall.getppid ();
}
public static UnixProcess GetParentProcess ()
{
return new UnixProcess (GetParentProcessId ());
}
public static string[] GetUserShells ()
{
ArrayList shells = new ArrayList ();
lock (Native.Syscall.usershell_lock) {
try {
if (Native.Syscall.setusershell () != 0)
UnixMarshal.ThrowExceptionForLastError ();
string shell;
while ((shell = Native.Syscall.getusershell ()) != null)
shells.Add (shell);
}
finally {
Native.Syscall.endusershell ();
}
}
return (string[]) shells.ToArray (typeof(string));
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,147 @@
//
// Mono.Unix/UnixFileInfo.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public sealed class UnixFileInfo : UnixFileSystemInfo
{
public UnixFileInfo (string path)
: base (path)
{
}
internal UnixFileInfo (string path, Native.Stat stat)
: base (path, stat)
{
}
public override string Name {
get {return UnixPath.GetFileName (FullPath);}
}
public string DirectoryName {
get {return UnixPath.GetDirectoryName (FullPath);}
}
public UnixDirectoryInfo Directory {
get {return new UnixDirectoryInfo (DirectoryName);}
}
public override void Delete ()
{
int r = Native.Syscall.unlink (FullPath);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
base.Refresh ();
}
public UnixStream Create ()
{
Native.FilePermissions mode = // 0644
Native.FilePermissions.S_IRUSR | Native.FilePermissions.S_IWUSR |
Native.FilePermissions.S_IRGRP | Native.FilePermissions.S_IROTH;
return Create (mode);
}
[CLSCompliant (false)]
public UnixStream Create (Native.FilePermissions mode)
{
int fd = Native.Syscall.creat (FullPath, mode);
if (fd < 0)
UnixMarshal.ThrowExceptionForLastError ();
base.Refresh ();
return new UnixStream (fd);
}
public UnixStream Create (FileAccessPermissions mode)
{
return Create ((Native.FilePermissions) mode);
}
[CLSCompliant (false)]
public UnixStream Open (Native.OpenFlags flags)
{
if ((flags & Native.OpenFlags.O_CREAT) != 0)
throw new ArgumentException (
"Cannot specify OpenFlags.O_CREAT without providing " +
"FilePermissions. Use the Open(OpenFlags, FilePermissions) " +
"method instead");
int fd = Native.Syscall.open (FullPath, flags);
if (fd < 0)
UnixMarshal.ThrowExceptionForLastError ();
return new UnixStream (fd);
}
[CLSCompliant (false)]
public UnixStream Open (Native.OpenFlags flags, Native.FilePermissions mode)
{
int fd = Native.Syscall.open (FullPath, flags, mode);
if (fd < 0)
UnixMarshal.ThrowExceptionForLastError ();
return new UnixStream (fd);
}
public UnixStream Open (FileMode mode)
{
Native.OpenFlags flags = Native.NativeConvert.ToOpenFlags (mode, FileAccess.ReadWrite);
return Open (flags);
}
public UnixStream Open (FileMode mode, FileAccess access)
{
Native.OpenFlags flags = Native.NativeConvert.ToOpenFlags (mode, access);
return Open (flags);
}
[CLSCompliant (false)]
public UnixStream Open (FileMode mode, FileAccess access, Native.FilePermissions perms)
{
Native.OpenFlags flags = Native.NativeConvert.ToOpenFlags (mode, access);
int fd = Native.Syscall.open (FullPath, flags, perms);
if (fd < 0)
UnixMarshal.ThrowExceptionForLastError ();
return new UnixStream (fd);
}
public UnixStream OpenRead ()
{
return Open (FileMode.Open, FileAccess.Read);
}
public UnixStream OpenWrite ()
{
return Open (FileMode.OpenOrCreate, FileAccess.Write);
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,428 @@
//
// Mono.Unix/UnixFileSystemInfo.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2006 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public abstract class UnixFileSystemInfo
{
private Native.Stat stat;
private string fullPath;
private string originalPath;
private bool valid = false;
internal const FileSpecialAttributes AllSpecialAttributes =
FileSpecialAttributes.SetUserId | FileSpecialAttributes.SetGroupId |
FileSpecialAttributes.Sticky;
internal const FileTypes AllFileTypes =
FileTypes.Directory | FileTypes.CharacterDevice | FileTypes.BlockDevice |
FileTypes.RegularFile | FileTypes.Fifo | FileTypes.SymbolicLink |
FileTypes.Socket;
protected UnixFileSystemInfo (string path)
{
UnixPath.CheckPath (path);
this.originalPath = path;
this.fullPath = UnixPath.GetFullPath (path);
Refresh (true);
}
internal UnixFileSystemInfo (String path, Native.Stat stat)
{
this.originalPath = path;
this.fullPath = UnixPath.GetFullPath (path);
this.stat = stat;
this.valid = true;
}
protected string FullPath {
get {return fullPath;}
set {
if (fullPath != value) {
UnixPath.CheckPath (value);
valid = false;
fullPath = value;
}
}
}
protected string OriginalPath {
get {return originalPath;}
set {originalPath = value;}
}
private void AssertValid ()
{
Refresh (false);
if (!valid)
throw new InvalidOperationException ("Path doesn't exist!");
}
public virtual string FullName {
get {return FullPath;}
}
public abstract string Name {get;}
public bool Exists {
get {
Refresh (true);
return valid;
}
}
public long Device {
get {AssertValid (); return Convert.ToInt64 (stat.st_dev);}
}
public long Inode {
get {AssertValid (); return Convert.ToInt64 (stat.st_ino);}
}
[CLSCompliant (false)]
public Native.FilePermissions Protection {
get {AssertValid (); return (Native.FilePermissions) stat.st_mode;}
set {
int r = Native.Syscall.chmod (FullPath, value);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
}
public FileTypes FileType {
get {
AssertValid ();
return (FileTypes) (stat.st_mode & Native.FilePermissions.S_IFMT);
}
// no set as chmod(2) won't accept changing the file type.
}
public FileAccessPermissions FileAccessPermissions {
get {
AssertValid ();
int perms = (int) stat.st_mode;
return (FileAccessPermissions) (perms & (int) FileAccessPermissions.AllPermissions);
}
set {
AssertValid ();
int perms = (int) stat.st_mode;
perms &= (int) ~FileAccessPermissions.AllPermissions;
perms |= (int) value;
Protection = (Native.FilePermissions) perms;
}
}
public FileSpecialAttributes FileSpecialAttributes {
get {
AssertValid ();
int attrs = (int) stat.st_mode;
return (FileSpecialAttributes) (attrs & (int) AllSpecialAttributes);
}
set {
AssertValid ();
int perms = (int) stat.st_mode;
perms &= (int) ~AllSpecialAttributes;
perms |= (int) value;
Protection = (Native.FilePermissions) perms;
}
}
public long LinkCount {
get {AssertValid (); return Convert.ToInt64 (stat.st_nlink);}
}
public UnixUserInfo OwnerUser {
get {AssertValid (); return new UnixUserInfo (stat.st_uid);}
}
public long OwnerUserId {
get {AssertValid (); return stat.st_uid;}
}
public UnixGroupInfo OwnerGroup {
get {AssertValid (); return new UnixGroupInfo (stat.st_gid);}
}
public long OwnerGroupId {
get {AssertValid (); return stat.st_gid;}
}
public long DeviceType {
get {AssertValid (); return Convert.ToInt64 (stat.st_rdev);}
}
public long Length {
get {AssertValid (); return (long) stat.st_size;}
}
public long BlockSize {
get {AssertValid (); return (long) stat.st_blksize;}
}
public long BlocksAllocated {
get {AssertValid (); return (long) stat.st_blocks;}
}
public DateTime LastAccessTime {
get {AssertValid (); return Native.NativeConvert.ToDateTime (stat.st_atime);}
}
public DateTime LastAccessTimeUtc {
get {return LastAccessTime.ToUniversalTime ();}
}
public DateTime LastWriteTime {
get {AssertValid (); return Native.NativeConvert.ToDateTime (stat.st_mtime);}
}
public DateTime LastWriteTimeUtc {
get {return LastWriteTime.ToUniversalTime ();}
}
public DateTime LastStatusChangeTime {
get {AssertValid (); return Native.NativeConvert.ToDateTime (stat.st_ctime);}
}
public DateTime LastStatusChangeTimeUtc {
get {return LastStatusChangeTime.ToUniversalTime ();}
}
public bool IsDirectory {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFDIR);}
}
public bool IsCharacterDevice {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFCHR);}
}
public bool IsBlockDevice {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFBLK);}
}
public bool IsRegularFile {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFREG);}
}
public bool IsFifo {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFIFO);}
}
public bool IsSymbolicLink {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFLNK);}
}
public bool IsSocket {
get {AssertValid (); return IsFileType (stat.st_mode, Native.FilePermissions.S_IFSOCK);}
}
public bool IsSetUser {
get {AssertValid (); return IsSet (stat.st_mode, Native.FilePermissions.S_ISUID);}
}
public bool IsSetGroup {
get {AssertValid (); return IsSet (stat.st_mode, Native.FilePermissions.S_ISGID);}
}
public bool IsSticky {
get {AssertValid (); return IsSet (stat.st_mode, Native.FilePermissions.S_ISVTX);}
}
internal static bool IsFileType (Native.FilePermissions mode, Native.FilePermissions type)
{
return (mode & Native.FilePermissions.S_IFMT) == type;
}
internal static bool IsSet (Native.FilePermissions mode, Native.FilePermissions type)
{
return (mode & type) == type;
}
[CLSCompliant (false)]
public bool CanAccess (Native.AccessModes mode)
{
int r = Native.Syscall.access (FullPath, mode);
return r == 0;
}
public UnixFileSystemInfo CreateLink (string path)
{
int r = Native.Syscall.link (FullName, path);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
return GetFileSystemEntry (path);
}
public UnixSymbolicLinkInfo CreateSymbolicLink (string path)
{
int r = Native.Syscall.symlink (FullName, path);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
return new UnixSymbolicLinkInfo (path);
}
public abstract void Delete ();
[CLSCompliant (false)]
public long GetConfigurationValue (Native.PathconfName name)
{
long r = Native.Syscall.pathconf (FullPath, name);
if (r == -1 && Native.Stdlib.GetLastError() != (Native.Errno) 0)
UnixMarshal.ThrowExceptionForLastError ();
return r;
}
public void Refresh ()
{
Refresh (true);
}
internal void Refresh (bool force)
{
if (valid && !force)
return;
valid = GetFileStatus (FullPath, out this.stat);
}
protected virtual bool GetFileStatus (string path, out Native.Stat stat)
{
return Native.Syscall.stat (path, out stat) == 0;
}
public void SetLength (long length)
{
int r;
do {
r = Native.Syscall.truncate (FullPath, length);
} while (UnixMarshal.ShouldRetrySyscall (r));
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public virtual void SetOwner (long owner, long group)
{
uint _owner = Convert.ToUInt32 (owner);
uint _group = Convert.ToUInt32 (group);
int r = Native.Syscall.chown (FullPath, _owner, _group);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public void SetOwner (string owner)
{
Native.Passwd pw = Native.Syscall.getpwnam (owner);
if (pw == null)
throw new ArgumentException (Locale.GetText ("invalid username"), "owner");
uint uid = pw.pw_uid;
uint gid = pw.pw_gid;
SetOwner ((long) uid, (long) gid);
}
public void SetOwner (string owner, string group)
{
long uid = -1;
if (owner != null)
uid = new UnixUserInfo (owner).UserId;
long gid = -1;
if (group != null)
gid = new UnixGroupInfo (group).GroupId;
SetOwner (uid, gid);
}
public void SetOwner (UnixUserInfo owner)
{
long uid, gid;
uid = gid = -1;
if (owner != null) {
uid = owner.UserId;
gid = owner.GroupId;
}
SetOwner (uid, gid);
}
public void SetOwner (UnixUserInfo owner, UnixGroupInfo group)
{
long uid, gid;
uid = gid = -1;
if (owner != null)
uid = owner.UserId;
if (group != null)
gid = owner.GroupId;
SetOwner (uid, gid);
}
public override string ToString ()
{
return FullPath;
}
public Native.Stat ToStat ()
{
AssertValid ();
return stat;
}
public static UnixFileSystemInfo GetFileSystemEntry (string path)
{
UnixFileSystemInfo info;
if (TryGetFileSystemEntry (path, out info))
return info;
UnixMarshal.ThrowExceptionForLastError ();
// Throw DirectoryNotFoundException because lstat(2) probably failed
// because of ENOTDIR (e.g. "/path/to/file/wtf"), so
// DirectoryNotFoundException is what would have been thrown anyway.
throw new DirectoryNotFoundException ("UnixMarshal.ThrowExceptionForLastError didn't throw?!");
}
public static bool TryGetFileSystemEntry (string path, out UnixFileSystemInfo entry)
{
Native.Stat stat;
int r = Native.Syscall.lstat (path, out stat);
if (r == -1) {
if (Native.Stdlib.GetLastError() == Native.Errno.ENOENT) {
entry = new UnixFileInfo (path);
return true;
}
entry = null;
return false;
}
if (IsFileType (stat.st_mode, Native.FilePermissions.S_IFDIR))
entry = new UnixDirectoryInfo (path, stat);
else if (IsFileType (stat.st_mode, Native.FilePermissions.S_IFLNK))
entry = new UnixSymbolicLinkInfo (path, stat);
else
entry = new UnixFileInfo (path, stat);
return true;
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,149 @@
//
// Mono.Unix/UnixGroupInfo.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2005 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public sealed class UnixGroupInfo
{
private Native.Group group;
public UnixGroupInfo (string group)
{
this.group = new Native.Group ();
Native.Group gr;
int r = Native.Syscall.getgrnam_r (group, this.group, out gr);
if (r != 0 || gr == null)
throw new ArgumentException (Locale.GetText ("invalid group name"), "group");
}
public UnixGroupInfo (long group)
{
this.group = new Native.Group ();
Native.Group gr;
int r = Native.Syscall.getgrgid_r (Convert.ToUInt32 (group), this.group, out gr);
if (r != 0 || gr == null)
throw new ArgumentException (Locale.GetText ("invalid group id"), "group");
}
public UnixGroupInfo (Native.Group group)
{
this.group = CopyGroup (group);
}
private static Native.Group CopyGroup (Native.Group group)
{
Native.Group g = new Native.Group ();
g.gr_gid = group.gr_gid;
g.gr_mem = group.gr_mem;
g.gr_name = group.gr_name;
g.gr_passwd = group.gr_passwd;
return g;
}
public string GroupName {
get {return group.gr_name;}
}
public string Password {
get {return group.gr_passwd;}
}
public long GroupId {
get {return group.gr_gid;}
}
public UnixUserInfo[] GetMembers ()
{
ArrayList members = new ArrayList (group.gr_mem.Length);
for (int i = 0; i < group.gr_mem.Length; ++i) {
try {
members.Add (new UnixUserInfo (group.gr_mem [i]));
} catch (ArgumentException) {
// ignore invalid users
}
}
return (UnixUserInfo[]) members.ToArray (typeof (UnixUserInfo));
}
public string[] GetMemberNames ()
{
return (string[]) group.gr_mem.Clone ();
}
public override int GetHashCode ()
{
return group.GetHashCode ();
}
public override bool Equals (object obj)
{
if (obj == null || GetType () != obj.GetType())
return false;
return group.Equals (((UnixGroupInfo) obj).group);
}
public override string ToString ()
{
return group.ToString();
}
public Native.Group ToGroup ()
{
return CopyGroup (group);
}
public static UnixGroupInfo[] GetLocalGroups ()
{
ArrayList entries = new ArrayList ();
lock (Native.Syscall.grp_lock) {
if (Native.Syscall.setgrent () != 0)
UnixMarshal.ThrowExceptionForLastError ();
try {
Native.Group g;
while ((g = Native.Syscall.getgrent()) != null)
entries.Add (new UnixGroupInfo (g));
if (Native.Syscall.GetLastError() != (Native.Errno) 0)
UnixMarshal.ThrowExceptionForLastError ();
}
finally {
Native.Syscall.endgrent ();
}
}
return (UnixGroupInfo[]) entries.ToArray (typeof(UnixGroupInfo));
}
}
}
// vim: noexpandtab

View File

@@ -0,0 +1,104 @@
//
// Mono.Unix/UnixIOException.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004-2005 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Mono.Unix;
namespace Mono.Unix {
[Serializable]
public class UnixIOException : IOException
{
private int errno;
public UnixIOException ()
: this (Marshal.GetLastWin32Error())
{}
public UnixIOException (int errno)
: base (GetMessage (Native.NativeConvert.ToErrno (errno)))
{
this.errno = errno;
}
public UnixIOException (int errno, Exception inner)
: base (GetMessage (Native.NativeConvert.ToErrno (errno)), inner)
{
this.errno = errno;
}
public UnixIOException (Native.Errno errno)
: base (GetMessage (errno))
{
this.errno = Native.NativeConvert.FromErrno (errno);
}
public UnixIOException (Native.Errno errno, Exception inner)
: base (GetMessage (errno), inner)
{
this.errno = Native.NativeConvert.FromErrno (errno);
}
public UnixIOException (string message)
: base (message)
{
this.errno = 0;
}
public UnixIOException (string message, Exception inner)
: base (message, inner)
{
this.errno = 0;
}
protected UnixIOException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
}
public int NativeErrorCode {
get {return errno;}
}
public Native.Errno ErrorCode {
get {return Native.NativeConvert.ToErrno (errno);}
}
private static string GetMessage (Native.Errno errno)
{
return string.Format ("{0} [{1}].",
UnixMarshal.GetErrorDescription (errno),
errno);
}
}
}
// vim: noexpandtab

Some files were not shown because too many files have changed in this diff Show More