2 // Mono.Unix/UnixStream.cs
5 // Jonathan Pryor (jonpryor@vt.edu)
7 // (C) 2004-2006 Jonathan Pryor
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Runtime.InteropServices;
37 public sealed class UnixStream : Stream, IDisposable
39 public const int InvalidFileDescriptor = -1;
40 public const int StandardInputFileDescriptor = 0;
41 public const int StandardOutputFileDescriptor = 1;
42 public const int StandardErrorFileDescriptor = 2;
44 public UnixStream (int fileDescriptor)
45 : this (fileDescriptor, true) {}
47 public UnixStream (int fileDescriptor, bool ownsHandle)
49 if (InvalidFileDescriptor == fileDescriptor)
50 throw new ArgumentException (Locale.GetText ("Invalid file descriptor"), "fileDescriptor");
52 this.fileDescriptor = fileDescriptor;
53 this.owner = ownsHandle;
55 long offset = Native.Syscall.lseek (fileDescriptor, 0, Native.SeekFlags.SEEK_CUR);
58 long read = Native.Syscall.read (fileDescriptor, IntPtr.Zero, 0);
61 long write = Native.Syscall.write (fileDescriptor, IntPtr.Zero, 0);
66 private void AssertNotDisposed ()
68 if (fileDescriptor == InvalidFileDescriptor)
69 throw new ObjectDisposedException ("Invalid File Descriptor");
73 get {return fileDescriptor;}
76 public override bool CanRead {
80 public override bool CanSeek {
84 public override bool CanWrite {
85 get {return canWrite;}
88 public override long Length {
92 throw new NotSupportedException ("File descriptor doesn't support seeking");
98 public override long Position {
100 AssertNotDisposed ();
102 throw new NotSupportedException ("The stream does not support seeking");
103 long pos = Native.Syscall.lseek (fileDescriptor, 0, Native.SeekFlags.SEEK_CUR);
105 UnixMarshal.ThrowExceptionForLastError ();
109 Seek (value, SeekOrigin.Begin);
113 [CLSCompliant (false)]
114 public Native.FilePermissions Protection {
120 // we can't change file type with fchmod, so clear out that portion
121 value &= ~Native.FilePermissions.S_IFMT;
122 int r = Native.Syscall.fchmod (fileDescriptor, value);
123 UnixMarshal.ThrowExceptionForLastErrorIf (r);
127 public FileTypes FileType {
129 int type = (int) Protection;
130 return (FileTypes) (type & (int) UnixFileSystemInfo.AllFileTypes);
132 // no set as fchmod(2) won't accept changing the file type.
135 public FileAccessPermissions FileAccessPermissions {
137 int perms = (int) Protection;
138 return (FileAccessPermissions) (perms & (int) FileAccessPermissions.AllPermissions);
141 int perms = (int) Protection;
142 perms &= (int) ~FileAccessPermissions.AllPermissions;
143 perms |= (int) value;
144 Protection = (Native.FilePermissions) perms;
148 public FileSpecialAttributes FileSpecialAttributes {
150 int attrs = (int) Protection;
151 return (FileSpecialAttributes) (attrs & (int) UnixFileSystemInfo.AllSpecialAttributes);
154 int perms = (int) Protection;
155 perms &= (int) ~UnixFileSystemInfo.AllSpecialAttributes;
156 perms |= (int) value;
157 Protection = (Native.FilePermissions) perms;
161 public UnixUserInfo OwnerUser {
162 get {RefreshStat (); return new UnixUserInfo (stat.st_uid);}
165 public long OwnerUserId {
166 get {RefreshStat (); return stat.st_uid;}
169 public UnixGroupInfo OwnerGroup {
170 get {RefreshStat (); return new UnixGroupInfo (stat.st_gid);}
173 public long OwnerGroupId {
174 get {RefreshStat (); return stat.st_gid;}
177 private void RefreshStat ()
179 AssertNotDisposed ();
180 int r = Native.Syscall.fstat (fileDescriptor, out stat);
181 UnixMarshal.ThrowExceptionForLastErrorIf (r);
184 public void AdviseFileAccessPattern (FileAccessPattern pattern, long offset, long len)
186 FileHandleOperations.AdviseFileAccessPattern (fileDescriptor, pattern, offset, len);
189 public void AdviseFileAccessPattern (FileAccessPattern pattern)
191 AdviseFileAccessPattern (pattern, 0, 0);
194 public override void Flush ()
198 public override unsafe int Read ([In, Out] byte[] buffer, int offset, int count)
200 AssertNotDisposed ();
201 AssertValidBuffer (buffer, offset, count);
203 throw new NotSupportedException ("Stream does not support reading");
206 fixed (byte* buf = &buffer[offset]) {
208 r = Native.Syscall.read (fileDescriptor, buf, (ulong) count);
209 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
212 UnixMarshal.ThrowExceptionForLastError ();
216 private void AssertValidBuffer (byte[] buffer, int offset, int count)
219 throw new ArgumentNullException ("buffer");
221 throw new ArgumentOutOfRangeException ("offset", "< 0");
223 throw new ArgumentOutOfRangeException ("count", "< 0");
224 if (offset > buffer.Length)
225 throw new ArgumentException ("destination offset is beyond array size");
226 if (offset > (buffer.Length - count))
227 throw new ArgumentException ("would overrun buffer");
230 public unsafe int ReadAtOffset ([In, Out] byte[] buffer,
231 int offset, int count, long fileOffset)
233 AssertNotDisposed ();
234 AssertValidBuffer (buffer, offset, count);
236 throw new NotSupportedException ("Stream does not support reading");
239 fixed (byte* buf = &buffer[offset]) {
241 r = Native.Syscall.pread (fileDescriptor, buf, (ulong) count, fileOffset);
242 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
245 UnixMarshal.ThrowExceptionForLastError ();
249 public override long Seek (long offset, SeekOrigin origin)
251 AssertNotDisposed ();
253 throw new NotSupportedException ("The File Descriptor does not support seeking");
254 if (offset > int.MaxValue)
255 throw new ArgumentOutOfRangeException ("offset", "too large");
257 Native.SeekFlags sf = Native.SeekFlags.SEEK_CUR;
259 case SeekOrigin.Begin: sf = Native.SeekFlags.SEEK_SET; break;
260 case SeekOrigin.Current: sf = Native.SeekFlags.SEEK_CUR; break;
261 case SeekOrigin.End: sf = Native.SeekFlags.SEEK_END; break;
264 long pos = Native.Syscall.lseek (fileDescriptor, offset, sf);
266 UnixMarshal.ThrowExceptionForLastError ();
270 public override void SetLength (long value)
272 AssertNotDisposed ();
274 throw new ArgumentOutOfRangeException ("value", "< 0");
275 if (!CanSeek && !CanWrite)
276 throw new NotSupportedException ("You can't truncating the current file descriptor");
280 r = Native.Syscall.ftruncate (fileDescriptor, value);
281 } while (UnixMarshal.ShouldRetrySyscall (r));
282 UnixMarshal.ThrowExceptionForLastErrorIf (r);
285 public override unsafe void Write (byte[] buffer, int offset, int count)
287 AssertNotDisposed ();
288 AssertValidBuffer (buffer, offset, count);
290 throw new NotSupportedException ("File Descriptor does not support writing");
293 fixed (byte* buf = &buffer[offset]) {
295 r = Native.Syscall.write (fileDescriptor, buf, (ulong) count);
296 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
299 UnixMarshal.ThrowExceptionForLastError ();
302 public unsafe void WriteAtOffset (byte[] buffer,
303 int offset, int count, long fileOffset)
305 AssertNotDisposed ();
306 AssertValidBuffer (buffer, offset, count);
308 throw new NotSupportedException ("File Descriptor does not support writing");
311 fixed (byte* buf = &buffer[offset]) {
313 r = Native.Syscall.pwrite (fileDescriptor, buf, (ulong) count, fileOffset);
314 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
317 UnixMarshal.ThrowExceptionForLastError ();
320 public void SendTo (UnixStream output)
322 SendTo (output, (ulong) output.Length);
325 [CLSCompliant (false)]
326 public void SendTo (UnixStream output, ulong count)
328 SendTo (output.Handle, count);
331 [CLSCompliant (false)]
332 public void SendTo (int out_fd, ulong count)
335 throw new NotSupportedException ("Unable to write to the current file descriptor");
336 long offset = Position;
337 long r = Native.Syscall.sendfile (out_fd, fileDescriptor, ref offset, count);
339 UnixMarshal.ThrowExceptionForLastError ();
342 public void SetOwner (long user, long group)
344 AssertNotDisposed ();
346 int r = Native.Syscall.fchown (fileDescriptor,
347 Convert.ToUInt32 (user), Convert.ToUInt32 (group));
348 UnixMarshal.ThrowExceptionForLastErrorIf (r);
351 public void SetOwner (string user, string group)
353 AssertNotDisposed ();
355 long uid = new UnixUserInfo (user).UserId;
356 long gid = new UnixGroupInfo (group).GroupId;
360 public void SetOwner (string user)
362 AssertNotDisposed ();
364 Native.Passwd pw = Native.Syscall.getpwnam (user);
366 throw new ArgumentException (Locale.GetText ("invalid username"), "user");
367 long uid = pw.pw_uid;
368 long gid = pw.pw_gid;
372 [CLSCompliant (false)]
373 public long GetConfigurationValue (Native.PathconfName name)
375 AssertNotDisposed ();
376 long r = Native.Syscall.fpathconf (fileDescriptor, name);
377 if (r == -1 && Native.Syscall.GetLastError() != (Native.Errno) 0)
378 UnixMarshal.ThrowExceptionForLastError ();
387 public override void Close ()
389 if (fileDescriptor == InvalidFileDescriptor)
399 r = Native.Syscall.close (fileDescriptor);
400 } while (UnixMarshal.ShouldRetrySyscall (r));
401 UnixMarshal.ThrowExceptionForLastErrorIf (r);
402 fileDescriptor = InvalidFileDescriptor;
403 GC.SuppressFinalize (this);
406 void IDisposable.Dispose ()
408 AssertNotDisposed ();
412 GC.SuppressFinalize (this);
415 private bool canSeek = false;
416 private bool canRead = false;
417 private bool canWrite = false;
418 private bool owner = true;
419 private int fileDescriptor = InvalidFileDescriptor;
420 private Native.Stat stat;