New test.
[mono.git] / mcs / class / Mono.Posix / Mono.Unix / UnixStream.cs
1 //
2 // Mono.Unix/UnixStream.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //
7 // (C) 2004-2006 Jonathan Pryor
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28
29 using System;
30 using System.IO;
31 using System.Runtime.InteropServices;
32 using System.Text;
33 using Mono.Unix;
34
35 namespace Mono.Unix {
36
37         public sealed class UnixStream : Stream, IDisposable
38         {
39                 public const int InvalidFileDescriptor = -1;
40                 public const int StandardInputFileDescriptor = 0;
41                 public const int StandardOutputFileDescriptor = 1;
42                 public const int StandardErrorFileDescriptor = 2;
43
44                 public UnixStream (int fileDescriptor)
45                         : this (fileDescriptor, true) {}
46
47                 public UnixStream (int fileDescriptor, bool ownsHandle)
48                 {
49                         if (InvalidFileDescriptor == fileDescriptor)
50                                 throw new ArgumentException (Locale.GetText ("Invalid file descriptor"), "fileDescriptor");
51                         
52                         this.fileDescriptor = fileDescriptor;
53                         this.owner = ownsHandle;
54                         
55                         long offset = Native.Syscall.lseek (fileDescriptor, 0, Native.SeekFlags.SEEK_CUR);
56                         if (offset != -1)
57                                 canSeek = true;
58                         long read = Native.Syscall.read (fileDescriptor, IntPtr.Zero, 0);
59                         if (read != -1)
60                                 canRead = true;
61                         long write = Native.Syscall.write (fileDescriptor, IntPtr.Zero, 0);
62                         if (write != -1)
63                                 canWrite = true;  
64                 }
65
66                 private void AssertNotDisposed ()
67                 {
68                         if (fileDescriptor == InvalidFileDescriptor)
69                                 throw new ObjectDisposedException ("Invalid File Descriptor");
70                 }
71
72                 public int Handle {
73                         get {return fileDescriptor;}
74                 }
75
76                 public override bool CanRead {
77                         get {return canRead;}
78                 }
79
80                 public override bool CanSeek {
81                         get {return canSeek;}
82                 }
83
84                 public override bool CanWrite {
85                         get {return canWrite;}
86                 }
87
88                 public override long Length {
89                         get {
90                                 AssertNotDisposed ();
91                                 if (!CanSeek)
92                                         throw new NotSupportedException ("File descriptor doesn't support seeking");
93                                 RefreshStat ();
94                                 return stat.st_size;
95                         }
96                 }
97
98                 public override long Position {
99                         get {
100                                 AssertNotDisposed ();
101                                 if (!CanSeek)
102                                         throw new NotSupportedException ("The stream does not support seeking");
103                                 long pos = Native.Syscall.lseek (fileDescriptor, 0, Native.SeekFlags.SEEK_CUR);
104                                 if (pos == -1)
105                                         UnixMarshal.ThrowExceptionForLastError ();
106                                 return (long) pos;
107                         }
108                         set {
109                                 Seek (value, SeekOrigin.Begin);
110                         }
111                 }
112
113                 [CLSCompliant (false)]
114                 public Native.FilePermissions Protection {
115                         get {
116                                 RefreshStat ();
117                                 return stat.st_mode;
118                         }
119                         set {
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);
124                         }
125                 }
126
127                 public FileTypes FileType {
128                         get {
129                                 int type = (int) Protection;
130                                 return (FileTypes) (type & (int) UnixFileSystemInfo.AllFileTypes);
131                         }
132                         // no set as fchmod(2) won't accept changing the file type.
133                 }
134
135                 public FileAccessPermissions FileAccessPermissions {
136                         get {
137                                 int perms = (int) Protection;
138                                 return (FileAccessPermissions) (perms & (int) FileAccessPermissions.AllPermissions);
139                         }
140                         set {
141                                 int perms = (int) Protection;
142                                 perms &= (int) ~FileAccessPermissions.AllPermissions;
143                                 perms |= (int) value;
144                                 Protection = (Native.FilePermissions) perms;
145                         }
146                 }
147
148                 public FileSpecialAttributes FileSpecialAttributes {
149                         get {
150                                 int attrs = (int) Protection;
151                                 return (FileSpecialAttributes) (attrs & (int) UnixFileSystemInfo.AllSpecialAttributes);
152                         }
153                         set {
154                                 int perms = (int) Protection;
155                                 perms &= (int) ~UnixFileSystemInfo.AllSpecialAttributes;
156                                 perms |= (int) value;
157                                 Protection = (Native.FilePermissions) perms;
158                         }
159                 }
160
161                 public UnixUserInfo OwnerUser {
162                         get {RefreshStat (); return new UnixUserInfo (stat.st_uid);}
163                 }
164                                                                                                 
165                 public long OwnerUserId {
166                         get {RefreshStat (); return stat.st_uid;}
167                 }
168                                                                                                 
169                 public UnixGroupInfo OwnerGroup {
170                         get {RefreshStat (); return new UnixGroupInfo (stat.st_gid);}
171                 }
172                                                                                                 
173                 public long OwnerGroupId {
174                         get {RefreshStat (); return stat.st_gid;}
175                 }
176
177                 private void RefreshStat ()
178                 {
179                         AssertNotDisposed ();
180                         int r = Native.Syscall.fstat (fileDescriptor, out stat);
181                         UnixMarshal.ThrowExceptionForLastErrorIf (r);
182                 }
183
184                 public void AdviseFileAccessPattern (FileAccessPattern pattern, long offset, long len)
185                 {
186                         FileHandleOperations.AdviseFileAccessPattern (fileDescriptor, pattern, offset, len);
187                 }
188
189                 public void AdviseFileAccessPattern (FileAccessPattern pattern)
190                 {
191                         AdviseFileAccessPattern (pattern, 0, 0);
192                 }
193
194                 public override void Flush ()
195                 {
196                 }
197
198                 public override unsafe int Read ([In, Out] byte[] buffer, int offset, int count)
199                 {
200                         AssertNotDisposed ();
201                         AssertValidBuffer (buffer, offset, count);
202                         if (!CanRead)
203                                 throw new NotSupportedException ("Stream does not support reading");
204                                  
205                         long r = 0;
206                         fixed (byte* buf = &buffer[offset]) {
207                                 do {
208                                         r = Native.Syscall.read (fileDescriptor, buf, (ulong) count);
209                                 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
210                         }
211                         if (r == -1)
212                                 UnixMarshal.ThrowExceptionForLastError ();
213                         return (int) r;
214                 }
215
216                 private void AssertValidBuffer (byte[] buffer, int offset, int count)
217                 {
218                         if (buffer == null)
219                                 throw new ArgumentNullException ("buffer");
220                         if (offset < 0)
221                                 throw new ArgumentOutOfRangeException ("offset", "< 0");
222                         if (count < 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");
228                 }
229
230                 public unsafe int ReadAtOffset ([In, Out] byte[] buffer, 
231                         int offset, int count, long fileOffset)
232                 {
233                         AssertNotDisposed ();
234                         AssertValidBuffer (buffer, offset, count);
235                         if (!CanRead)
236                                 throw new NotSupportedException ("Stream does not support reading");
237                                  
238                         long r = 0;
239                         fixed (byte* buf = &buffer[offset]) {
240                                 do {
241                                         r = Native.Syscall.pread (fileDescriptor, buf, (ulong) count, fileOffset);
242                                 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
243                         }
244                         if (r == -1)
245                                 UnixMarshal.ThrowExceptionForLastError ();
246                         return (int) r;
247                 }
248
249                 public override long Seek (long offset, SeekOrigin origin)
250                 {
251                         AssertNotDisposed ();
252                         if (!CanSeek)
253                                 throw new NotSupportedException ("The File Descriptor does not support seeking");
254                         if (offset > int.MaxValue)
255                                 throw new ArgumentOutOfRangeException ("offset", "too large");
256                                         
257                         Native.SeekFlags sf = Native.SeekFlags.SEEK_CUR;
258                         switch (origin) {
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;
262                         }
263
264                         long pos = Native.Syscall.lseek (fileDescriptor, offset, sf);
265                         if (pos == -1)
266                                 UnixMarshal.ThrowExceptionForLastError ();
267                         return (long) pos;
268                 }
269
270                 public override void SetLength (long value)
271                 {
272                         AssertNotDisposed ();
273                         if (value < 0)
274                                 throw new ArgumentOutOfRangeException ("value", "< 0");
275                         if (!CanSeek && !CanWrite)
276                                 throw new NotSupportedException ("You can't truncating the current file descriptor");
277                         
278                         int r;
279                         do {
280                                 r = Native.Syscall.ftruncate (fileDescriptor, value);
281                         } while (UnixMarshal.ShouldRetrySyscall (r));
282                         UnixMarshal.ThrowExceptionForLastErrorIf (r);
283                 }
284
285                 public override unsafe void Write (byte[] buffer, int offset, int count)
286                 {
287                         AssertNotDisposed ();
288                         AssertValidBuffer (buffer, offset, count);
289                         if (!CanWrite)
290                                 throw new NotSupportedException ("File Descriptor does not support writing");
291
292                         long r = 0;
293                         fixed (byte* buf = &buffer[offset]) {
294                                 do {
295                                         r = Native.Syscall.write (fileDescriptor, buf, (ulong) count);
296                                 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
297                         }
298                         if (r == -1)
299                                 UnixMarshal.ThrowExceptionForLastError ();
300                 }
301                 
302                 public unsafe void WriteAtOffset (byte[] buffer, 
303                         int offset, int count, long fileOffset)
304                 {
305                         AssertNotDisposed ();
306                         AssertValidBuffer (buffer, offset, count);
307                         if (!CanWrite)
308                                 throw new NotSupportedException ("File Descriptor does not support writing");
309
310                         long r = 0;
311                         fixed (byte* buf = &buffer[offset]) {
312                                 do {
313                                         r = Native.Syscall.pwrite (fileDescriptor, buf, (ulong) count, fileOffset);
314                                 } while (UnixMarshal.ShouldRetrySyscall ((int) r));
315                         }
316                         if (r == -1)
317                                 UnixMarshal.ThrowExceptionForLastError ();
318                 }
319
320                 public void SendTo (UnixStream output)
321                 {
322                         SendTo (output, (ulong) output.Length);
323                 }
324
325                 [CLSCompliant (false)]
326                 public void SendTo (UnixStream output, ulong count)
327                 {
328                         SendTo (output.Handle, count);
329                 }
330
331                 [CLSCompliant (false)]
332                 public void SendTo (int out_fd, ulong count)
333                 {
334                         if (!CanWrite)
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);
338                         if (r == -1)
339                                 UnixMarshal.ThrowExceptionForLastError ();
340                 }
341                 
342                 public void SetOwner (long user, long group)
343                 {
344                         AssertNotDisposed ();
345
346                         int r = Native.Syscall.fchown (fileDescriptor, 
347                                         Convert.ToUInt32 (user), Convert.ToUInt32 (group));
348                         UnixMarshal.ThrowExceptionForLastErrorIf (r);
349                 }
350
351                 public void SetOwner (string user, string group)
352                 {
353                         AssertNotDisposed ();
354
355                         long uid = new UnixUserInfo (user).UserId;
356                         long gid = new UnixGroupInfo (group).GroupId;
357                         SetOwner (uid, gid);
358                 }
359
360                 public void SetOwner (string user)
361                 {
362                         AssertNotDisposed ();
363
364                         Native.Passwd pw = Native.Syscall.getpwnam (user);
365                         if (pw == null)
366                                 throw new ArgumentException (Locale.GetText ("invalid username"), "user");
367                         long uid = pw.pw_uid;
368                         long gid = pw.pw_gid;
369                         SetOwner (uid, gid);
370                 }
371
372                 [CLSCompliant (false)]
373                 public long GetConfigurationValue (Native.PathconfName name)
374                 {
375                         AssertNotDisposed ();
376                         long r = Native.Syscall.fpathconf (fileDescriptor, name);
377                         if (r == -1 && Native.Syscall.GetLastError() != (Native.Errno) 0)
378                                 UnixMarshal.ThrowExceptionForLastError ();
379                         return r;
380                 }
381
382                 ~UnixStream ()
383                 {
384                         Close ();
385                 }
386
387                 public override void Close ()
388                 {
389                         if (fileDescriptor == InvalidFileDescriptor)
390                                 return;
391                                 
392                         Flush ();
393
394                         if (!owner)
395                                 return;
396
397                         int r;
398                         do {
399                                 r = Native.Syscall.close (fileDescriptor);
400                         } while (UnixMarshal.ShouldRetrySyscall (r));
401                         UnixMarshal.ThrowExceptionForLastErrorIf (r);
402                         fileDescriptor = InvalidFileDescriptor;
403                         GC.SuppressFinalize (this);
404                 }
405                 
406                 void IDisposable.Dispose ()
407                 {
408                         AssertNotDisposed ();
409                         if (owner) {
410                                 Close ();
411                         }
412                         GC.SuppressFinalize (this);
413                 }
414
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;
421         }
422 }
423
424 // vim: noexpandtab