Let the system figure our permissions instead of doing a poor job at it.
[mono.git] / mono / io-layer / io.c
1 /*
2  * io.c:  File, console and find handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  * Copyright (c) 2002-2006 Novell, Inc.
9  */
10
11 #include <config.h>
12 #include <glib.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <sys/stat.h>
18 #ifdef HAVE_SYS_STATVFS_H
19 #include <sys/statvfs.h>
20 #endif
21 #if defined(HAVE_SYS_STATFS_H)
22 #include <sys/statfs.h>
23 #endif
24 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
25 #include <sys/param.h>
26 #include <sys/mount.h>
27 #endif
28 #include <sys/types.h>
29 #include <dirent.h>
30 #include <fnmatch.h>
31 #include <stdio.h>
32 #include <utime.h>
33 #ifdef __linux__
34 #include <sys/ioctl.h>
35 #include <linux/fs.h>
36 #include <mono/utils/linux_magic.h>
37 #endif
38
39 #include <mono/io-layer/wapi.h>
40 #include <mono/io-layer/wapi-private.h>
41 #include <mono/io-layer/handles-private.h>
42 #include <mono/io-layer/io-private.h>
43 #include <mono/io-layer/timefuncs-private.h>
44 #include <mono/io-layer/thread-private.h>
45 #include <mono/io-layer/io-portability.h>
46 #include <mono/utils/strenc.h>
47
48 #undef DEBUG
49
50 static void file_close (gpointer handle, gpointer data);
51 static WapiFileType file_getfiletype(void);
52 static gboolean file_read(gpointer handle, gpointer buffer,
53                           guint32 numbytes, guint32 *bytesread,
54                           WapiOverlapped *overlapped);
55 static gboolean file_write(gpointer handle, gconstpointer buffer,
56                            guint32 numbytes, guint32 *byteswritten,
57                            WapiOverlapped *overlapped);
58 static gboolean file_flush(gpointer handle);
59 static guint32 file_seek(gpointer handle, gint32 movedistance,
60                          gint32 *highmovedistance, WapiSeekMethod method);
61 static gboolean file_setendoffile(gpointer handle);
62 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
63 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
64                                  WapiFileTime *last_access,
65                                  WapiFileTime *last_write);
66 static gboolean file_setfiletime(gpointer handle,
67                                  const WapiFileTime *create_time,
68                                  const WapiFileTime *last_access,
69                                  const WapiFileTime *last_write);
70 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
71
72 /* File handle is only signalled for overlapped IO */
73 struct _WapiHandleOps _wapi_file_ops = {
74         file_close,             /* close */
75         NULL,                   /* signal */
76         NULL,                   /* own */
77         NULL,                   /* is_owned */
78         NULL,                   /* special_wait */
79         NULL                    /* prewait */
80 };
81
82 void _wapi_file_details (gpointer handle_info)
83 {
84         struct _WapiHandle_file *file = (struct _WapiHandle_file *)handle_info;
85         
86         g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
87                  file->filename,
88                  file->fileaccess&GENERIC_READ?'R':'.',
89                  file->fileaccess&GENERIC_WRITE?'W':'.',
90                  file->fileaccess&GENERIC_EXECUTE?'X':'.',
91                  file->sharemode&FILE_SHARE_READ?'R':'.',
92                  file->sharemode&FILE_SHARE_WRITE?'W':'.',
93                  file->sharemode&FILE_SHARE_DELETE?'D':'.',
94                  file->attrs);
95 }
96
97 static void console_close (gpointer handle, gpointer data);
98 static WapiFileType console_getfiletype(void);
99 static gboolean console_read(gpointer handle, gpointer buffer,
100                              guint32 numbytes, guint32 *bytesread,
101                              WapiOverlapped *overlapped);
102 static gboolean console_write(gpointer handle, gconstpointer buffer,
103                               guint32 numbytes, guint32 *byteswritten,
104                               WapiOverlapped *overlapped);
105
106 /* Console is mostly the same as file, except it can block waiting for
107  * input or output
108  */
109 struct _WapiHandleOps _wapi_console_ops = {
110         console_close,          /* close */
111         NULL,                   /* signal */
112         NULL,                   /* own */
113         NULL,                   /* is_owned */
114         NULL,                   /* special_wait */
115         NULL                    /* prewait */
116 };
117
118 void _wapi_console_details (gpointer handle_info)
119 {
120         _wapi_file_details (handle_info);
121 }
122
123 /* Find handle has no ops.
124  */
125 struct _WapiHandleOps _wapi_find_ops = {
126         NULL,                   /* close */
127         NULL,                   /* signal */
128         NULL,                   /* own */
129         NULL,                   /* is_owned */
130         NULL,                   /* special_wait */
131         NULL                    /* prewait */
132 };
133
134 static void pipe_close (gpointer handle, gpointer data);
135 static WapiFileType pipe_getfiletype (void);
136 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes,
137                            guint32 *bytesread, WapiOverlapped *overlapped);
138 static gboolean pipe_write (gpointer handle, gconstpointer buffer,
139                             guint32 numbytes, guint32 *byteswritten,
140                             WapiOverlapped *overlapped);
141
142 /* Pipe handles
143  */
144 struct _WapiHandleOps _wapi_pipe_ops = {
145         pipe_close,             /* close */
146         NULL,                   /* signal */
147         NULL,                   /* own */
148         NULL,                   /* is_owned */
149         NULL,                   /* special_wait */
150         NULL                    /* prewait */
151 };
152
153 void _wapi_pipe_details (gpointer handle_info)
154 {
155         _wapi_file_details (handle_info);
156 }
157
158 static const struct {
159         /* File, console and pipe handles */
160         WapiFileType (*getfiletype)(void);
161         
162         /* File, console and pipe handles */
163         gboolean (*readfile)(gpointer handle, gpointer buffer,
164                              guint32 numbytes, guint32 *bytesread,
165                              WapiOverlapped *overlapped);
166         gboolean (*writefile)(gpointer handle, gconstpointer buffer,
167                               guint32 numbytes, guint32 *byteswritten,
168                               WapiOverlapped *overlapped);
169         gboolean (*flushfile)(gpointer handle);
170         
171         /* File handles */
172         guint32 (*seek)(gpointer handle, gint32 movedistance,
173                         gint32 *highmovedistance, WapiSeekMethod method);
174         gboolean (*setendoffile)(gpointer handle);
175         guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
176         gboolean (*getfiletime)(gpointer handle, WapiFileTime *create_time,
177                                 WapiFileTime *last_access,
178                                 WapiFileTime *last_write);
179         gboolean (*setfiletime)(gpointer handle,
180                                 const WapiFileTime *create_time,
181                                 const WapiFileTime *last_access,
182                                 const WapiFileTime *last_write);
183 } io_ops[WAPI_HANDLE_COUNT]={
184         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
185         /* file */
186         {file_getfiletype,
187          file_read, file_write,
188          file_flush, file_seek,
189          file_setendoffile,
190          file_getfilesize,
191          file_getfiletime,
192          file_setfiletime},
193         /* console */
194         {console_getfiletype,
195          console_read,
196          console_write,
197          NULL, NULL, NULL, NULL, NULL, NULL},
198         /* thread */
199         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
200         /* sem */
201         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
202         /* mutex */
203         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
204         /* event */
205         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
206         /* socket (will need at least read and write) */
207         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
208         /* find */
209         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
210         /* process */
211         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
212         /* pipe */
213         {pipe_getfiletype,
214          pipe_read,
215          pipe_write,
216          NULL, NULL, NULL, NULL, NULL, NULL},
217 };
218
219 static mono_once_t io_ops_once=MONO_ONCE_INIT;
220 static gboolean lock_while_writing = FALSE;
221
222 static void io_ops_init (void)
223 {
224 /*      _wapi_handle_register_capabilities (WAPI_HANDLE_FILE, */
225 /*                                          WAPI_HANDLE_CAP_WAIT); */
226 /*      _wapi_handle_register_capabilities (WAPI_HANDLE_CONSOLE, */
227 /*                                          WAPI_HANDLE_CAP_WAIT); */
228
229         if (g_getenv ("MONO_STRICT_IO_EMULATION") != NULL) {
230                 lock_while_writing = TRUE;
231         }
232 }
233
234 /* Some utility functions.
235  */
236
237 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
238                                               struct stat *buf,
239                                               struct stat *lbuf)
240 {
241         guint32 attrs = 0;
242         gchar *filename;
243         
244         /* FIXME: this could definitely be better, but there seems to
245          * be no pattern to the attributes that are set
246          */
247
248         /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
249         if (S_ISSOCK (buf->st_mode))
250                 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
251
252         filename = _wapi_basename (pathname);
253
254         if (S_ISDIR (buf->st_mode)) {
255                 attrs = FILE_ATTRIBUTE_DIRECTORY;
256                 if (!(buf->st_mode & S_IWUSR)) {
257                         attrs |= FILE_ATTRIBUTE_READONLY;
258                 }
259                 if (filename[0] == '.') {
260                         attrs |= FILE_ATTRIBUTE_HIDDEN;
261                 }
262         } else {
263                 if (!(buf->st_mode & S_IWUSR)) {
264                         attrs = FILE_ATTRIBUTE_READONLY;
265
266                         if (filename[0] == '.') {
267                                 attrs |= FILE_ATTRIBUTE_HIDDEN;
268                         }
269                 } else if (filename[0] == '.') {
270                         attrs = FILE_ATTRIBUTE_HIDDEN;
271                 } else {
272                         attrs = FILE_ATTRIBUTE_NORMAL;
273                 }
274         }
275
276         if (lbuf != NULL) {
277                 if (S_ISLNK (lbuf->st_mode)) {
278                         attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
279                 }
280         }
281         
282         g_free (filename);
283         
284         return attrs;
285 }
286
287 static void
288 _wapi_set_last_error_from_errno (void)
289 {
290         SetLastError (_wapi_get_win32_file_error (errno));
291 }
292
293 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
294                                                   const gchar *path)
295 {
296         if (errno == ENOENT) {
297                 /* Check the path - if it's a missing directory then
298                  * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
299                  */
300                 gchar *dirname;
301
302
303                 if (dir == NULL) {
304                         dirname = _wapi_dirname (path);
305                 } else {
306                         dirname = g_strdup (dir);
307                 }
308                 
309                 if (_wapi_access (dirname, F_OK) == 0) {
310                         SetLastError (ERROR_FILE_NOT_FOUND);
311                 } else {
312                         SetLastError (ERROR_PATH_NOT_FOUND);
313                 }
314
315                 g_free (dirname);
316         } else {
317                 _wapi_set_last_error_from_errno ();
318         }
319 }
320
321 /* Handle ops.
322  */
323 static void file_close (gpointer handle, gpointer data)
324 {
325         struct _WapiHandle_file *file_handle = (struct _WapiHandle_file *)data;
326         
327 #ifdef DEBUG
328         g_message("%s: closing file handle %p [%s]", __func__, handle,
329                   file_handle->filename);
330 #endif
331
332         if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
333                 _wapi_unlink (file_handle->filename);
334         
335         g_free (file_handle->filename);
336         
337         if (file_handle->share_info)
338                 _wapi_handle_share_release (file_handle->share_info);
339         
340         close (GPOINTER_TO_UINT(handle));
341 }
342
343 static WapiFileType file_getfiletype(void)
344 {
345         return(FILE_TYPE_DISK);
346 }
347
348 static gboolean file_read(gpointer handle, gpointer buffer,
349                           guint32 numbytes, guint32 *bytesread,
350                           WapiOverlapped *overlapped)
351 {
352         struct _WapiHandle_file *file_handle;
353         gboolean ok;
354         int fd = GPOINTER_TO_UINT(handle);
355         int ret;
356         
357         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
358                                 (gpointer *)&file_handle);
359         if(ok==FALSE) {
360                 g_warning ("%s: error looking up file handle %p", __func__,
361                            handle);
362                 SetLastError (ERROR_INVALID_HANDLE);
363                 return(FALSE);
364         }
365
366         if(bytesread!=NULL) {
367                 *bytesread=0;
368         }
369         
370         if(!(file_handle->fileaccess & GENERIC_READ) &&
371            !(file_handle->fileaccess & GENERIC_ALL)) {
372 #ifdef DEBUG
373                 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
374                           __func__, handle, file_handle->fileaccess);
375 #endif
376
377                 SetLastError (ERROR_ACCESS_DENIED);
378                 return(FALSE);
379         }
380
381         do {
382                 ret = read (fd, buffer, numbytes);
383         } while (ret == -1 && errno == EINTR &&
384                  !_wapi_thread_cur_apc_pending());
385                         
386         if(ret==-1) {
387                 gint err = errno;
388
389 #ifdef DEBUG
390                 g_message("%s: read of handle %p error: %s", __func__,
391                           handle, strerror(err));
392 #endif
393                 SetLastError (_wapi_get_win32_file_error (err));
394                 return(FALSE);
395         }
396                 
397         if (bytesread != NULL) {
398                 *bytesread = ret;
399         }
400                 
401         return(TRUE);
402 }
403
404 static gboolean file_write(gpointer handle, gconstpointer buffer,
405                            guint32 numbytes, guint32 *byteswritten,
406                            WapiOverlapped *overlapped G_GNUC_UNUSED)
407 {
408         struct _WapiHandle_file *file_handle;
409         gboolean ok;
410         int ret;
411         off_t current_pos = 0;
412         int fd = GPOINTER_TO_UINT(handle);
413         
414         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
415                                 (gpointer *)&file_handle);
416         if(ok==FALSE) {
417                 g_warning ("%s: error looking up file handle %p", __func__,
418                            handle);
419                 SetLastError (ERROR_INVALID_HANDLE);
420                 return(FALSE);
421         }
422         
423         if(byteswritten!=NULL) {
424                 *byteswritten=0;
425         }
426         
427         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
428            !(file_handle->fileaccess & GENERIC_ALL)) {
429 #ifdef DEBUG
430                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
431 #endif
432
433                 SetLastError (ERROR_ACCESS_DENIED);
434                 return(FALSE);
435         }
436         
437         if (lock_while_writing) {
438                 /* Need to lock the region we're about to write to,
439                  * because we only do advisory locking on POSIX
440                  * systems
441                  */
442                 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
443                 if (current_pos == -1) {
444 #ifdef DEBUG
445                         g_message ("%s: handle %p lseek failed: %s", __func__,
446                                    handle, strerror (errno));
447 #endif
448                         _wapi_set_last_error_from_errno ();
449                         return(FALSE);
450                 }
451                 
452                 if (_wapi_lock_file_region (fd, current_pos,
453                                             numbytes) == FALSE) {
454                         /* The error has already been set */
455                         return(FALSE);
456                 }
457         }
458                 
459         do {
460                 ret = write (fd, buffer, numbytes);
461         } while (ret == -1 && errno == EINTR &&
462                  !_wapi_thread_cur_apc_pending());
463         
464         if (lock_while_writing) {
465                 _wapi_unlock_file_region (fd, current_pos, numbytes);
466         }
467
468         if (ret == -1) {
469                 if (errno == EINTR) {
470                         ret = 0;
471                 } else {
472                         _wapi_set_last_error_from_errno ();
473                                 
474 #ifdef DEBUG
475                         g_message("%s: write of handle %p error: %s",
476                                   __func__, handle, strerror(errno));
477 #endif
478
479                         return(FALSE);
480                 }
481         }
482         if (byteswritten != NULL) {
483                 *byteswritten = ret;
484         }
485         return(TRUE);
486 }
487
488 static gboolean file_flush(gpointer handle)
489 {
490         struct _WapiHandle_file *file_handle;
491         gboolean ok;
492         int ret;
493         int fd = GPOINTER_TO_UINT(handle);
494         
495         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
496                                 (gpointer *)&file_handle);
497         if(ok==FALSE) {
498                 g_warning ("%s: error looking up file handle %p", __func__,
499                            handle);
500                 SetLastError (ERROR_INVALID_HANDLE);
501                 return(FALSE);
502         }
503
504         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
505            !(file_handle->fileaccess & GENERIC_ALL)) {
506 #ifdef DEBUG
507                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
508 #endif
509
510                 SetLastError (ERROR_ACCESS_DENIED);
511                 return(FALSE);
512         }
513
514         ret=fsync(fd);
515         if (ret==-1) {
516 #ifdef DEBUG
517                 g_message("%s: fsync of handle %p error: %s", __func__, handle,
518                           strerror(errno));
519 #endif
520
521                 _wapi_set_last_error_from_errno ();
522                 return(FALSE);
523         }
524         
525         return(TRUE);
526 }
527
528 static guint32 file_seek(gpointer handle, gint32 movedistance,
529                          gint32 *highmovedistance, WapiSeekMethod method)
530 {
531         struct _WapiHandle_file *file_handle;
532         gboolean ok;
533         off_t offset, newpos;
534         int whence;
535         guint32 ret;
536         int fd = GPOINTER_TO_UINT(handle);
537         
538         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
539                                 (gpointer *)&file_handle);
540         if(ok==FALSE) {
541                 g_warning ("%s: error looking up file handle %p", __func__,
542                            handle);
543                 SetLastError (ERROR_INVALID_HANDLE);
544                 return(INVALID_SET_FILE_POINTER);
545         }
546         
547         if(!(file_handle->fileaccess & GENERIC_READ) &&
548            !(file_handle->fileaccess & GENERIC_WRITE) &&
549            !(file_handle->fileaccess & GENERIC_ALL)) {
550 #ifdef DEBUG
551                 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
552 #endif
553
554                 SetLastError (ERROR_ACCESS_DENIED);
555                 return(INVALID_SET_FILE_POINTER);
556         }
557
558         switch(method) {
559         case FILE_BEGIN:
560                 whence=SEEK_SET;
561                 break;
562         case FILE_CURRENT:
563                 whence=SEEK_CUR;
564                 break;
565         case FILE_END:
566                 whence=SEEK_END;
567                 break;
568         default:
569 #ifdef DEBUG
570                 g_message("%s: invalid seek type %d", __func__, method);
571 #endif
572
573                 SetLastError (ERROR_INVALID_PARAMETER);
574                 return(INVALID_SET_FILE_POINTER);
575         }
576
577 #ifdef HAVE_LARGE_FILE_SUPPORT
578         if(highmovedistance==NULL) {
579                 offset=movedistance;
580 #ifdef DEBUG
581                 g_message("%s: setting offset to %lld (low %d)", __func__,
582                           offset, movedistance);
583 #endif
584         } else {
585                 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
586                 
587 #ifdef DEBUG
588                 g_message("%s: setting offset to %lld 0x%llx (high %d 0x%x, low %d 0x%x)", __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
589 #endif
590         }
591 #else
592         offset=movedistance;
593 #endif
594
595 #ifdef DEBUG
596 #ifdef HAVE_LARGE_FILE_SUPPORT
597         g_message("%s: moving handle %p by %lld bytes from %d", __func__,
598                   handle, offset, whence);
599 #else
600         g_message("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
601                   handle, offset, whence);
602 #endif
603 #endif
604
605         newpos=lseek(fd, offset, whence);
606         if(newpos==-1) {
607 #ifdef DEBUG
608                 g_message("%s: lseek on handle %p returned error %s",
609                           __func__, handle, strerror(errno));
610 #endif
611
612                 _wapi_set_last_error_from_errno ();
613                 return(INVALID_SET_FILE_POINTER);
614         }
615
616 #ifdef DEBUG
617 #ifdef HAVE_LARGE_FILE_SUPPORT
618         g_message("%s: lseek returns %lld", __func__, newpos);
619 #else
620         g_message ("%s: lseek returns %ld", __func__, newpos);
621 #endif
622 #endif
623
624 #ifdef HAVE_LARGE_FILE_SUPPORT
625         ret=newpos & 0xFFFFFFFF;
626         if(highmovedistance!=NULL) {
627                 *highmovedistance=newpos>>32;
628         }
629 #else
630         ret=newpos;
631         if(highmovedistance!=NULL) {
632                 /* Accurate, but potentially dodgy :-) */
633                 *highmovedistance=0;
634         }
635 #endif
636
637 #ifdef DEBUG
638         g_message ("%s: move of handle %p returning %d/%d", __func__,
639                    handle, ret, highmovedistance==NULL?0:*highmovedistance);
640 #endif
641
642         return(ret);
643 }
644
645 static gboolean file_setendoffile(gpointer handle)
646 {
647         struct _WapiHandle_file *file_handle;
648         gboolean ok;
649         struct stat statbuf;
650         off_t size, pos;
651         int ret;
652         int fd = GPOINTER_TO_UINT(handle);
653         
654         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
655                                 (gpointer *)&file_handle);
656         if(ok==FALSE) {
657                 g_warning ("%s: error looking up file handle %p", __func__,
658                            handle);
659                 SetLastError (ERROR_INVALID_HANDLE);
660                 return(FALSE);
661         }
662         
663         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
664            !(file_handle->fileaccess & GENERIC_ALL)) {
665 #ifdef DEBUG
666                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
667 #endif
668
669                 SetLastError (ERROR_ACCESS_DENIED);
670                 return(FALSE);
671         }
672
673         /* Find the current file position, and the file length.  If
674          * the file position is greater than the length, write to
675          * extend the file with a hole.  If the file position is less
676          * than the length, truncate the file.
677          */
678         
679         ret=fstat(fd, &statbuf);
680         if(ret==-1) {
681 #ifdef DEBUG
682                 g_message ("%s: handle %p fstat failed: %s", __func__,
683                            handle, strerror(errno));
684 #endif
685
686                 _wapi_set_last_error_from_errno ();
687                 return(FALSE);
688         }
689         size=statbuf.st_size;
690
691         pos=lseek(fd, (off_t)0, SEEK_CUR);
692         if(pos==-1) {
693 #ifdef DEBUG
694                 g_message("%s: handle %p lseek failed: %s", __func__,
695                           handle, strerror(errno));
696 #endif
697
698                 _wapi_set_last_error_from_errno ();
699                 return(FALSE);
700         }
701         
702 #ifdef FTRUNCATE_DOESNT_EXTEND
703         /* I haven't bothered to write the configure.in stuff for this
704          * because I don't know if any platform needs it.  I'm leaving
705          * this code just in case though
706          */
707         if(pos>size) {
708                 /* Extend the file.  Use write() here, because some
709                  * manuals say that ftruncate() behaviour is undefined
710                  * when the file needs extending.  The POSIX spec says
711                  * that on XSI-conformant systems it extends, so if
712                  * every system we care about conforms, then we can
713                  * drop this write.
714                  */
715                 do {
716                         ret = write (fd, "", 1);
717                 } while (ret == -1 && errno == EINTR &&
718                          !_wapi_thread_cur_apc_pending());
719
720                 if(ret==-1) {
721 #ifdef DEBUG
722                         g_message("%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
723 #endif
724
725                         _wapi_set_last_error_from_errno ();
726                         return(FALSE);
727                 }
728
729                 /* And put the file position back after the write */
730                 ret = lseek (fd, pos, SEEK_SET);
731                 if (ret == -1) {
732 #ifdef DEBUG
733                         g_message ("%s: handle %p second lseek failed: %s",
734                                    __func__, handle, strerror(errno));
735 #endif
736
737                         _wapi_set_last_error_from_errno ();
738                         return(FALSE);
739                 }
740         }
741 #endif
742
743         /* always truncate, because the extend write() adds an extra
744          * byte to the end of the file
745          */
746         do {
747                 ret=ftruncate(fd, pos);
748         }
749         while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending()); 
750         if(ret==-1) {
751 #ifdef DEBUG
752                 g_message("%s: handle %p ftruncate failed: %s", __func__,
753                           handle, strerror(errno));
754 #endif
755                 
756                 _wapi_set_last_error_from_errno ();
757                 return(FALSE);
758         }
759                 
760         return(TRUE);
761 }
762
763 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
764 {
765         struct _WapiHandle_file *file_handle;
766         gboolean ok;
767         struct stat statbuf;
768         guint32 size;
769         int ret;
770         int fd = GPOINTER_TO_UINT(handle);
771         
772         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
773                                 (gpointer *)&file_handle);
774         if(ok==FALSE) {
775                 g_warning ("%s: error looking up file handle %p", __func__,
776                            handle);
777                 SetLastError (ERROR_INVALID_HANDLE);
778                 return(INVALID_FILE_SIZE);
779         }
780         
781         if(!(file_handle->fileaccess & GENERIC_READ) &&
782            !(file_handle->fileaccess & GENERIC_WRITE) &&
783            !(file_handle->fileaccess & GENERIC_ALL)) {
784 #ifdef DEBUG
785                 g_message("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
786 #endif
787
788                 SetLastError (ERROR_ACCESS_DENIED);
789                 return(INVALID_FILE_SIZE);
790         }
791
792         /* If the file has a size with the low bits 0xFFFFFFFF the
793          * caller can't tell if this is an error, so clear the error
794          * value
795          */
796         SetLastError (ERROR_SUCCESS);
797         
798         ret = fstat(fd, &statbuf);
799         if (ret == -1) {
800 #ifdef DEBUG
801                 g_message ("%s: handle %p fstat failed: %s", __func__,
802                            handle, strerror(errno));
803 #endif
804
805                 _wapi_set_last_error_from_errno ();
806                 return(INVALID_FILE_SIZE);
807         }
808         
809         /* fstat indicates block devices as zero-length, so go a different path */
810 #ifdef BLKGETSIZE64
811         if (S_ISBLK(statbuf.st_mode)) {
812                 guint64 bigsize;
813                 if (ioctl(fd, BLKGETSIZE64, &bigsize) < 0) {
814 #ifdef DEBUG
815                         g_message ("%s: handle %p ioctl BLKGETSIZE64 failed: %s",
816                                    __func__, handle, strerror(errno));
817 #endif
818
819                         _wapi_set_last_error_from_errno ();
820                         return(INVALID_FILE_SIZE);
821                 }
822                 
823                 size = bigsize & 0xFFFFFFFF;
824                 if (highsize != NULL) {
825                         *highsize = bigsize>>32;
826                 }
827
828 #ifdef DEBUG
829                 g_message ("%s: Returning block device size %d/%d",
830                            __func__, size, *highsize);
831 #endif
832         
833                 return(size);
834         }
835 #endif
836         
837 #ifdef HAVE_LARGE_FILE_SUPPORT
838         size = statbuf.st_size & 0xFFFFFFFF;
839         if (highsize != NULL) {
840                 *highsize = statbuf.st_size>>32;
841         }
842 #else
843         if (highsize != NULL) {
844                 /* Accurate, but potentially dodgy :-) */
845                 *highsize = 0;
846         }
847         size = statbuf.st_size;
848 #endif
849
850 #ifdef DEBUG
851         g_message ("%s: Returning size %d/%d", __func__, size, *highsize);
852 #endif
853         
854         return(size);
855 }
856
857 static gboolean file_getfiletime(gpointer handle, WapiFileTime *create_time,
858                                  WapiFileTime *last_access,
859                                  WapiFileTime *last_write)
860 {
861         struct _WapiHandle_file *file_handle;
862         gboolean ok;
863         struct stat statbuf;
864         guint64 create_ticks, access_ticks, write_ticks;
865         int ret;
866         int fd = GPOINTER_TO_UINT(handle);
867         
868         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
869                                 (gpointer *)&file_handle);
870         if(ok==FALSE) {
871                 g_warning ("%s: error looking up file handle %p", __func__,
872                            handle);
873                 SetLastError (ERROR_INVALID_HANDLE);
874                 return(FALSE);
875         }
876
877         if(!(file_handle->fileaccess & GENERIC_READ) &&
878            !(file_handle->fileaccess & GENERIC_ALL)) {
879 #ifdef DEBUG
880                 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
881                           __func__, handle, file_handle->fileaccess);
882 #endif
883
884                 SetLastError (ERROR_ACCESS_DENIED);
885                 return(FALSE);
886         }
887         
888         ret=fstat(fd, &statbuf);
889         if(ret==-1) {
890 #ifdef DEBUG
891                 g_message("%s: handle %p fstat failed: %s", __func__, handle,
892                           strerror(errno));
893 #endif
894
895                 _wapi_set_last_error_from_errno ();
896                 return(FALSE);
897         }
898
899 #ifdef DEBUG
900         g_message("%s: atime: %ld ctime: %ld mtime: %ld", __func__,
901                   statbuf.st_atime, statbuf.st_ctime,
902                   statbuf.st_mtime);
903 #endif
904
905         /* Try and guess a meaningful create time by using the older
906          * of atime or ctime
907          */
908         /* The magic constant comes from msdn documentation
909          * "Converting a time_t Value to a File Time"
910          */
911         if(statbuf.st_atime < statbuf.st_ctime) {
912                 create_ticks=((guint64)statbuf.st_atime*10000000)
913                         + 116444736000000000ULL;
914         } else {
915                 create_ticks=((guint64)statbuf.st_ctime*10000000)
916                         + 116444736000000000ULL;
917         }
918         
919         access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
920         write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
921         
922 #ifdef DEBUG
923         g_message("%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
924                   access_ticks, create_ticks, write_ticks);
925 #endif
926
927         if(create_time!=NULL) {
928                 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
929                 create_time->dwHighDateTime = create_ticks >> 32;
930         }
931         
932         if(last_access!=NULL) {
933                 last_access->dwLowDateTime = access_ticks & 0xFFFFFFFF;
934                 last_access->dwHighDateTime = access_ticks >> 32;
935         }
936         
937         if(last_write!=NULL) {
938                 last_write->dwLowDateTime = write_ticks & 0xFFFFFFFF;
939                 last_write->dwHighDateTime = write_ticks >> 32;
940         }
941
942         return(TRUE);
943 }
944
945 static gboolean file_setfiletime(gpointer handle,
946                                  const WapiFileTime *create_time G_GNUC_UNUSED,
947                                  const WapiFileTime *last_access,
948                                  const WapiFileTime *last_write)
949 {
950         struct _WapiHandle_file *file_handle;
951         gboolean ok;
952         struct utimbuf utbuf;
953         struct stat statbuf;
954         guint64 access_ticks, write_ticks;
955         int ret;
956         int fd = GPOINTER_TO_UINT(handle);
957         
958         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
959                                 (gpointer *)&file_handle);
960         if(ok==FALSE) {
961                 g_warning ("%s: error looking up file handle %p", __func__,
962                            handle);
963                 SetLastError (ERROR_INVALID_HANDLE);
964                 return(FALSE);
965         }
966         
967         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
968            !(file_handle->fileaccess & GENERIC_ALL)) {
969 #ifdef DEBUG
970                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
971 #endif
972
973                 SetLastError (ERROR_ACCESS_DENIED);
974                 return(FALSE);
975         }
976
977         if(file_handle->filename == NULL) {
978 #ifdef DEBUG
979                 g_message("%s: handle %p unknown filename", __func__, handle);
980 #endif
981
982                 SetLastError (ERROR_INVALID_HANDLE);
983                 return(FALSE);
984         }
985         
986         /* Get the current times, so we can put the same times back in
987          * the event that one of the FileTime structs is NULL
988          */
989         ret=fstat (fd, &statbuf);
990         if(ret==-1) {
991 #ifdef DEBUG
992                 g_message("%s: handle %p fstat failed: %s", __func__, handle,
993                           strerror(errno));
994 #endif
995
996                 SetLastError (ERROR_INVALID_PARAMETER);
997                 return(FALSE);
998         }
999
1000         if(last_access!=NULL) {
1001                 access_ticks=((guint64)last_access->dwHighDateTime << 32) +
1002                         last_access->dwLowDateTime;
1003                 /* This is (time_t)0.  We can actually go to INT_MIN,
1004                  * but this will do for now.
1005                  */
1006                 if (access_ticks < 116444736000000000ULL) {
1007 #ifdef DEBUG
1008                         g_message ("%s: attempt to set access time too early",
1009                                    __func__);
1010 #endif
1011                         SetLastError (ERROR_INVALID_PARAMETER);
1012                         return(FALSE);
1013                 }
1014                 
1015                 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1016         } else {
1017                 utbuf.actime=statbuf.st_atime;
1018         }
1019
1020         if(last_write!=NULL) {
1021                 write_ticks=((guint64)last_write->dwHighDateTime << 32) +
1022                         last_write->dwLowDateTime;
1023                 /* This is (time_t)0.  We can actually go to INT_MIN,
1024                  * but this will do for now.
1025                  */
1026                 if (write_ticks < 116444736000000000ULL) {
1027 #ifdef DEBUG
1028                         g_message ("%s: attempt to set write time too early",
1029                                    __func__);
1030 #endif
1031                         SetLastError (ERROR_INVALID_PARAMETER);
1032                         return(FALSE);
1033                 }
1034                 
1035                 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1036         } else {
1037                 utbuf.modtime=statbuf.st_mtime;
1038         }
1039
1040 #ifdef DEBUG
1041         g_message ("%s: setting handle %p access %ld write %ld", __func__,
1042                    handle, utbuf.actime, utbuf.modtime);
1043 #endif
1044
1045         ret = _wapi_utime (file_handle->filename, &utbuf);
1046         if (ret == -1) {
1047 #ifdef DEBUG
1048                 g_message ("%s: handle %p [%s] utime failed: %s", __func__,
1049                            handle, file_handle->filename, strerror(errno));
1050
1051 #endif
1052                 SetLastError (ERROR_INVALID_PARAMETER);
1053                 return(FALSE);
1054         }
1055         
1056         return(TRUE);
1057 }
1058
1059 static void console_close (gpointer handle, gpointer data)
1060 {
1061         struct _WapiHandle_file *console_handle = (struct _WapiHandle_file *)data;
1062         
1063 #ifdef DEBUG
1064         g_message("%s: closing console handle %p", __func__, handle);
1065 #endif
1066
1067         g_free (console_handle->filename);
1068         
1069         close (GPOINTER_TO_UINT(handle));
1070 }
1071
1072 static WapiFileType console_getfiletype(void)
1073 {
1074         return(FILE_TYPE_CHAR);
1075 }
1076
1077 static gboolean console_read(gpointer handle, gpointer buffer,
1078                              guint32 numbytes, guint32 *bytesread,
1079                              WapiOverlapped *overlapped G_GNUC_UNUSED)
1080 {
1081         struct _WapiHandle_file *console_handle;
1082         gboolean ok;
1083         int ret;
1084         int fd = GPOINTER_TO_UINT(handle);
1085         
1086         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1087                                 (gpointer *)&console_handle);
1088         if(ok==FALSE) {
1089                 g_warning ("%s: error looking up console handle %p", __func__,
1090                            handle);
1091                 SetLastError (ERROR_INVALID_HANDLE);
1092                 return(FALSE);
1093         }
1094         
1095         if(bytesread!=NULL) {
1096                 *bytesread=0;
1097         }
1098         
1099         if(!(console_handle->fileaccess & GENERIC_READ) &&
1100            !(console_handle->fileaccess & GENERIC_ALL)) {
1101 #ifdef DEBUG
1102                 g_message ("%s: handle %p doesn't have GENERIC_READ access: %u",
1103                            __func__, handle, console_handle->fileaccess);
1104 #endif
1105
1106                 SetLastError (ERROR_ACCESS_DENIED);
1107                 return(FALSE);
1108         }
1109         
1110         do {
1111                 ret=read(fd, buffer, numbytes);
1112         } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1113
1114         if(ret==-1) {
1115 #ifdef DEBUG
1116                 g_message("%s: read of handle %p error: %s", __func__, handle,
1117                           strerror(errno));
1118 #endif
1119
1120                 _wapi_set_last_error_from_errno ();
1121                 return(FALSE);
1122         }
1123         
1124         if(bytesread!=NULL) {
1125                 *bytesread=ret;
1126         }
1127         
1128         return(TRUE);
1129 }
1130
1131 static gboolean console_write(gpointer handle, gconstpointer buffer,
1132                               guint32 numbytes, guint32 *byteswritten,
1133                               WapiOverlapped *overlapped G_GNUC_UNUSED)
1134 {
1135         struct _WapiHandle_file *console_handle;
1136         gboolean ok;
1137         int ret;
1138         int fd = GPOINTER_TO_UINT(handle);
1139         
1140         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
1141                                 (gpointer *)&console_handle);
1142         if(ok==FALSE) {
1143                 g_warning ("%s: error looking up console handle %p", __func__,
1144                            handle);
1145                 SetLastError (ERROR_INVALID_HANDLE);
1146                 return(FALSE);
1147         }
1148         
1149         if(byteswritten!=NULL) {
1150                 *byteswritten=0;
1151         }
1152         
1153         if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1154            !(console_handle->fileaccess & GENERIC_ALL)) {
1155 #ifdef DEBUG
1156                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1157 #endif
1158
1159                 SetLastError (ERROR_ACCESS_DENIED);
1160                 return(FALSE);
1161         }
1162         
1163         do {
1164                 ret = write(fd, buffer, numbytes);
1165         } while (ret == -1 && errno == EINTR &&
1166                  !_wapi_thread_cur_apc_pending());
1167
1168         if (ret == -1) {
1169                 if (errno == EINTR) {
1170                         ret = 0;
1171                 } else {
1172                         _wapi_set_last_error_from_errno ();
1173                         
1174 #ifdef DEBUG
1175                         g_message ("%s: write of handle %p error: %s",
1176                                    __func__, handle, strerror(errno));
1177 #endif
1178
1179                         return(FALSE);
1180                 }
1181         }
1182         if(byteswritten!=NULL) {
1183                 *byteswritten=ret;
1184         }
1185         
1186         return(TRUE);
1187 }
1188
1189 static void pipe_close (gpointer handle, gpointer data G_GNUC_UNUSED)
1190 {
1191 #ifdef DEBUG
1192         g_message("%s: closing pipe handle %p", __func__, handle);
1193 #endif
1194
1195         /* No filename with pipe handles */
1196
1197         close(GPOINTER_TO_UINT(handle));
1198 }
1199
1200 static WapiFileType pipe_getfiletype(void)
1201 {
1202         return(FILE_TYPE_PIPE);
1203 }
1204
1205 static gboolean pipe_read (gpointer handle, gpointer buffer,
1206                            guint32 numbytes, guint32 *bytesread,
1207                            WapiOverlapped *overlapped G_GNUC_UNUSED)
1208 {
1209         struct _WapiHandle_file *pipe_handle;
1210         gboolean ok;
1211         int ret;
1212         int fd = GPOINTER_TO_UINT(handle);
1213         
1214         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1215                                 (gpointer *)&pipe_handle);
1216         if(ok==FALSE) {
1217                 g_warning ("%s: error looking up pipe handle %p", __func__,
1218                            handle);
1219                 SetLastError (ERROR_INVALID_HANDLE);
1220                 return(FALSE);
1221         }
1222
1223         if(bytesread!=NULL) {
1224                 *bytesread=0;
1225         }
1226         
1227         if(!(pipe_handle->fileaccess & GENERIC_READ) &&
1228            !(pipe_handle->fileaccess & GENERIC_ALL)) {
1229 #ifdef DEBUG
1230                 g_message("%s: handle %p doesn't have GENERIC_READ access: %u",
1231                           __func__, handle, pipe_handle->fileaccess);
1232 #endif
1233
1234                 SetLastError (ERROR_ACCESS_DENIED);
1235                 return(FALSE);
1236         }
1237         
1238 #ifdef DEBUG
1239         g_message ("%s: reading up to %d bytes from pipe %p", __func__,
1240                    numbytes, handle);
1241 #endif
1242
1243         do {
1244                 ret=read(fd, buffer, numbytes);
1245         } while (ret==-1 && errno==EINTR && !_wapi_thread_cur_apc_pending());
1246                 
1247         if (ret == -1) {
1248                 if (errno == EINTR) {
1249                         ret = 0;
1250                 } else {
1251                         _wapi_set_last_error_from_errno ();
1252                         
1253 #ifdef DEBUG
1254                         g_message("%s: read of handle %p error: %s", __func__,
1255                                   handle, strerror(errno));
1256 #endif
1257
1258                         return(FALSE);
1259                 }
1260         }
1261         
1262 #ifdef DEBUG
1263         g_message ("%s: read %d bytes from pipe", __func__, ret);
1264 #endif
1265
1266         if(bytesread!=NULL) {
1267                 *bytesread=ret;
1268         }
1269         
1270         return(TRUE);
1271 }
1272
1273 static gboolean pipe_write(gpointer handle, gconstpointer buffer,
1274                            guint32 numbytes, guint32 *byteswritten,
1275                            WapiOverlapped *overlapped G_GNUC_UNUSED)
1276 {
1277         struct _WapiHandle_file *pipe_handle;
1278         gboolean ok;
1279         int ret;
1280         int fd = GPOINTER_TO_UINT(handle);
1281         
1282         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PIPE,
1283                                 (gpointer *)&pipe_handle);
1284         if(ok==FALSE) {
1285                 g_warning ("%s: error looking up pipe handle %p", __func__,
1286                            handle);
1287                 SetLastError (ERROR_INVALID_HANDLE);
1288                 return(FALSE);
1289         }
1290         
1291         if(byteswritten!=NULL) {
1292                 *byteswritten=0;
1293         }
1294         
1295         if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
1296            !(pipe_handle->fileaccess & GENERIC_ALL)) {
1297 #ifdef DEBUG
1298                 g_message("%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
1299 #endif
1300
1301                 SetLastError (ERROR_ACCESS_DENIED);
1302                 return(FALSE);
1303         }
1304         
1305 #ifdef DEBUG
1306         g_message ("%s: writing up to %d bytes to pipe %p", __func__, numbytes,
1307                    handle);
1308 #endif
1309
1310         do {
1311                 ret = write (fd, buffer, numbytes);
1312         } while (ret == -1 && errno == EINTR &&
1313                  !_wapi_thread_cur_apc_pending());
1314
1315         if (ret == -1) {
1316                 if (errno == EINTR) {
1317                         ret = 0;
1318                 } else {
1319                         _wapi_set_last_error_from_errno ();
1320                         
1321 #ifdef DEBUG
1322                         g_message("%s: write of handle %p error: %s", __func__,
1323                                   handle, strerror(errno));
1324 #endif
1325
1326                         return(FALSE);
1327                 }
1328         }
1329         if(byteswritten!=NULL) {
1330                 *byteswritten=ret;
1331         }
1332         
1333         return(TRUE);
1334 }
1335
1336 static int convert_flags(guint32 fileaccess, guint32 createmode)
1337 {
1338         int flags=0;
1339         
1340         switch(fileaccess) {
1341         case GENERIC_READ:
1342                 flags=O_RDONLY;
1343                 break;
1344         case GENERIC_WRITE:
1345                 flags=O_WRONLY;
1346                 break;
1347         case GENERIC_READ|GENERIC_WRITE:
1348                 flags=O_RDWR;
1349                 break;
1350         default:
1351 #ifdef DEBUG
1352                 g_message("%s: Unknown access type 0x%x", __func__,
1353                           fileaccess);
1354 #endif
1355                 break;
1356         }
1357
1358         switch(createmode) {
1359         case CREATE_NEW:
1360                 flags|=O_CREAT|O_EXCL;
1361                 break;
1362         case CREATE_ALWAYS:
1363                 flags|=O_CREAT|O_TRUNC;
1364                 break;
1365         case OPEN_EXISTING:
1366                 break;
1367         case OPEN_ALWAYS:
1368                 flags|=O_CREAT;
1369                 break;
1370         case TRUNCATE_EXISTING:
1371                 flags|=O_TRUNC;
1372                 break;
1373         default:
1374 #ifdef DEBUG
1375                 g_message("%s: Unknown create mode 0x%x", __func__,
1376                           createmode);
1377 #endif
1378                 break;
1379         }
1380         
1381         return(flags);
1382 }
1383
1384 #if 0 /* unused */
1385 static mode_t convert_perms(guint32 sharemode)
1386 {
1387         mode_t perms=0600;
1388         
1389         if(sharemode&FILE_SHARE_READ) {
1390                 perms|=044;
1391         }
1392         if(sharemode&FILE_SHARE_WRITE) {
1393                 perms|=022;
1394         }
1395
1396         return(perms);
1397 }
1398 #endif
1399
1400 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
1401                                    guint32 fileaccess,
1402                                    struct _WapiFileShare **share_info)
1403 {
1404         gboolean file_already_shared;
1405         guint32 file_existing_share, file_existing_access;
1406
1407         file_already_shared = _wapi_handle_get_or_set_share (statbuf->st_dev, statbuf->st_ino, sharemode, fileaccess, &file_existing_share, &file_existing_access, share_info);
1408         
1409         if (file_already_shared) {
1410                 /* The reference to this share info was incremented
1411                  * when we looked it up, so be careful to put it back
1412                  * if we conclude we can't use this file.
1413                  */
1414                 if (file_existing_share == 0) {
1415                         /* Quick and easy, no possibility to share */
1416 #ifdef DEBUG
1417                         g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
1418 #endif
1419
1420                         _wapi_handle_share_release (*share_info);
1421                         
1422                         return(FALSE);
1423                 }
1424
1425                 if (((file_existing_share == FILE_SHARE_READ) &&
1426                      (fileaccess != GENERIC_READ)) ||
1427                     ((file_existing_share == FILE_SHARE_WRITE) &&
1428                      (fileaccess != GENERIC_WRITE))) {
1429                         /* New access mode doesn't match up */
1430 #ifdef DEBUG
1431                         g_message ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
1432 #endif
1433
1434                         _wapi_handle_share_release (*share_info);
1435                 
1436                         return(FALSE);
1437                 }
1438
1439                 if (((file_existing_access & GENERIC_READ) &&
1440                      !(sharemode & FILE_SHARE_READ)) ||
1441                     ((file_existing_access & GENERIC_WRITE) &&
1442                      !(sharemode & FILE_SHARE_WRITE))) {
1443                         /* New share mode doesn't match up */
1444 #ifdef DEBUG
1445                         g_message ("%s: Access mode prevents open: requested share: 0x%x, file has access: 0x%x", __func__, sharemode, file_existing_access);
1446 #endif
1447
1448                         _wapi_handle_share_release (*share_info);
1449                 
1450                         return(FALSE);
1451                 }
1452         } else {
1453 #ifdef DEBUG
1454                 g_message ("%s: New file!", __func__);
1455 #endif
1456         }
1457
1458         return(TRUE);
1459 }
1460
1461 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
1462                              guint32 fileaccess,
1463                              struct _WapiFileShare **share_info, int fd)
1464 {
1465         if (share_allows_open (statbuf, sharemode, fileaccess,
1466                                share_info) == TRUE) {
1467                 return (TRUE);
1468         }
1469         
1470         /* Got a share violation.  Double check that the file is still
1471          * open by someone, in case a process crashed while still
1472          * holding a file handle.  This will also cope with someone
1473          * using Mono.Posix to close the file.  This is cheaper and
1474          * less intrusive to other processes than initiating a handle
1475          * collection.
1476          */
1477
1478         _wapi_handle_check_share (*share_info, fd);
1479         if (share_allows_open (statbuf, sharemode, fileaccess,
1480                                share_info) == TRUE) {
1481                 return (TRUE);
1482         }
1483         
1484         /* Still violating.  It's possible that a process crashed
1485          * while still holding a file handle, and that a non-mono
1486          * process has the file open.  (For example, C-c mcs while
1487          * editing a source file.)  As a last resort, run a handle
1488          * collection, which will remove stale share entries.
1489          */
1490         _wapi_handle_collect ();
1491
1492         return(share_allows_open (statbuf, sharemode, fileaccess, share_info));
1493 }
1494
1495 /**
1496  * CreateFile:
1497  * @name: a pointer to a NULL-terminated unicode string, that names
1498  * the file or other object to create.
1499  * @fileaccess: specifies the file access mode
1500  * @sharemode: whether the file should be shared.  This parameter is
1501  * currently ignored.
1502  * @security: Ignored for now.
1503  * @createmode: specifies whether to create a new file, whether to
1504  * overwrite an existing file, whether to truncate the file, etc.
1505  * @attrs: specifies file attributes and flags.  On win32 attributes
1506  * are characteristics of the file, not the handle, and are ignored
1507  * when an existing file is opened.  Flags give the library hints on
1508  * how to process a file to optimise performance.
1509  * @template: the handle of an open %GENERIC_READ file that specifies
1510  * attributes to apply to a newly created file, ignoring @attrs.
1511  * Normally this parameter is NULL.  This parameter is ignored when an
1512  * existing file is opened.
1513  *
1514  * Creates a new file handle.  This only applies to normal files:
1515  * pipes are handled by CreatePipe(), and console handles are created
1516  * with GetStdHandle().
1517  *
1518  * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1519  */
1520 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1521                     guint32 sharemode, WapiSecurityAttributes *security,
1522                     guint32 createmode, guint32 attrs,
1523                     gpointer template G_GNUC_UNUSED)
1524 {
1525         struct _WapiHandle_file file_handle = {0};
1526         gpointer handle;
1527         int flags=convert_flags(fileaccess, createmode);
1528         /*mode_t perms=convert_perms(sharemode);*/
1529         /* we don't use sharemode, because that relates to sharing of
1530          * the file when the file is open and is already handled by
1531          * other code, perms instead are the on-disk permissions and
1532          * this is a sane default.
1533          */
1534         mode_t perms=0666;
1535         gchar *filename;
1536         int fd, ret;
1537         int handle_type;
1538         struct stat statbuf;
1539         
1540         mono_once (&io_ops_once, io_ops_init);
1541
1542         if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1543                 perms = 0600;
1544         
1545         if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1546                 SetLastError (ERROR_ENCRYPTION_FAILED);
1547                 return INVALID_HANDLE_VALUE;
1548         }
1549         
1550         if (name == NULL) {
1551 #ifdef DEBUG
1552                 g_message ("%s: name is NULL", __func__);
1553 #endif
1554
1555                 SetLastError (ERROR_INVALID_NAME);
1556                 return(INVALID_HANDLE_VALUE);
1557         }
1558
1559         filename = mono_unicode_to_external (name);
1560         if (filename == NULL) {
1561 #ifdef DEBUG
1562                 g_message("%s: unicode conversion returned NULL", __func__);
1563 #endif
1564
1565                 SetLastError (ERROR_INVALID_NAME);
1566                 return(INVALID_HANDLE_VALUE);
1567         }
1568         
1569 #ifdef DEBUG
1570         g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1571                    filename, sharemode, fileaccess);
1572 #endif
1573         
1574         fd = _wapi_open (filename, flags, perms);
1575     
1576         /* If we were trying to open a directory with write permissions
1577          * (e.g. O_WRONLY or O_RDWR), this call will fail with
1578          * EISDIR. However, this is a bit bogus because calls to
1579          * manipulate the directory (e.g. SetFileTime) will still work on
1580          * the directory because they use other API calls
1581          * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1582          * to open the directory again without write permission.
1583          */
1584         if (fd == -1 && errno == EISDIR)
1585         {
1586                 /* Try again but don't try to make it writable */
1587                 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1588         }
1589         
1590         if (fd == -1) {
1591 #ifdef DEBUG
1592                 g_message("%s: Error opening file %s: %s", __func__, filename,
1593                           strerror(errno));
1594 #endif
1595                 _wapi_set_last_path_error_from_errno (NULL, filename);
1596                 g_free (filename);
1597
1598                 return(INVALID_HANDLE_VALUE);
1599         }
1600
1601         if (fd >= _wapi_fd_reserve) {
1602 #ifdef DEBUG
1603                 g_message ("%s: File descriptor is too big", __func__);
1604 #endif
1605
1606                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1607                 
1608                 close (fd);
1609                 g_free (filename);
1610                 
1611                 return(INVALID_HANDLE_VALUE);
1612         }
1613
1614         ret = fstat (fd, &statbuf);
1615         if (ret == -1) {
1616 #ifdef DEBUG
1617                 g_message ("%s: fstat error of file %s: %s", __func__,
1618                            filename, strerror (errno));
1619 #endif
1620                 _wapi_set_last_error_from_errno ();
1621                 g_free (filename);
1622                 close (fd);
1623                 
1624                 return(INVALID_HANDLE_VALUE);
1625         }
1626
1627         if (share_check (&statbuf, sharemode, fileaccess,
1628                          &file_handle.share_info, fd) == FALSE) {
1629                 SetLastError (ERROR_SHARING_VIOLATION);
1630                 g_free (filename);
1631                 close (fd);
1632                 
1633                 return (INVALID_HANDLE_VALUE);
1634         }
1635         if (file_handle.share_info == NULL) {
1636                 /* No space, so no more files can be opened */
1637 #ifdef DEBUG
1638                 g_message ("%s: No space in the share table", __func__);
1639 #endif
1640
1641                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1642                 close (fd);
1643                 g_free (filename);
1644                 
1645                 return(INVALID_HANDLE_VALUE);
1646         }
1647         
1648         file_handle.filename = filename;
1649
1650         if(security!=NULL) {
1651                 //file_handle->security_attributes=_wapi_handle_scratch_store (
1652                 //security, sizeof(WapiSecurityAttributes));
1653         }
1654         
1655         file_handle.fileaccess=fileaccess;
1656         file_handle.sharemode=sharemode;
1657         file_handle.attrs=attrs;
1658
1659 #ifdef HAVE_POSIX_FADVISE
1660         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1661                 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1662         if (attrs & FILE_FLAG_RANDOM_ACCESS)
1663                 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1664 #endif
1665         
1666 #ifndef S_ISFIFO
1667 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1668 #endif
1669         if (S_ISFIFO (statbuf.st_mode)) {
1670                 handle_type = WAPI_HANDLE_PIPE;
1671         } else if (S_ISCHR (statbuf.st_mode)) {
1672                 handle_type = WAPI_HANDLE_CONSOLE;
1673         } else {
1674                 handle_type = WAPI_HANDLE_FILE;
1675         }
1676
1677         handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1678         if (handle == _WAPI_HANDLE_INVALID) {
1679                 g_warning ("%s: error creating file handle", __func__);
1680                 g_free (filename);
1681                 close (fd);
1682                 
1683                 SetLastError (ERROR_GEN_FAILURE);
1684                 return(INVALID_HANDLE_VALUE);
1685         }
1686         
1687 #ifdef DEBUG
1688         g_message("%s: returning handle %p", __func__, handle);
1689 #endif
1690         
1691         return(handle);
1692 }
1693
1694 /**
1695  * DeleteFile:
1696  * @name: a pointer to a NULL-terminated unicode string, that names
1697  * the file to be deleted.
1698  *
1699  * Deletes file @name.
1700  *
1701  * Return value: %TRUE on success, %FALSE otherwise.
1702  */
1703 gboolean DeleteFile(const gunichar2 *name)
1704 {
1705         gchar *filename;
1706         int retval;
1707         gboolean ret = FALSE;
1708         guint32 attrs;
1709 #if 0
1710         struct stat statbuf;
1711         struct _WapiFileShare *shareinfo;
1712 #endif
1713         
1714         if(name==NULL) {
1715 #ifdef DEBUG
1716                 g_message("%s: name is NULL", __func__);
1717 #endif
1718
1719                 SetLastError (ERROR_INVALID_NAME);
1720                 return(FALSE);
1721         }
1722
1723         filename=mono_unicode_to_external(name);
1724         if(filename==NULL) {
1725 #ifdef DEBUG
1726                 g_message("%s: unicode conversion returned NULL", __func__);
1727 #endif
1728
1729                 SetLastError (ERROR_INVALID_NAME);
1730                 return(FALSE);
1731         }
1732
1733         attrs = GetFileAttributes (name);
1734         if (attrs == INVALID_FILE_ATTRIBUTES) {
1735 #ifdef DEBUG
1736                 g_message ("%s: file attributes error", __func__);
1737 #endif
1738                 /* Error set by GetFileAttributes() */
1739                 g_free (filename);
1740                 return(FALSE);
1741         }
1742
1743 #if 0
1744         /* Check to make sure sharing allows us to open the file for
1745          * writing.  See bug 323389.
1746          *
1747          * Do the checks that don't need an open file descriptor, for
1748          * simplicity's sake.  If we really have to do the full checks
1749          * then we can implement that later.
1750          */
1751         if (_wapi_stat (filename, &statbuf) < 0) {
1752                 _wapi_set_last_path_error_from_errno (NULL, filename);
1753                 g_free (filename);
1754                 return(FALSE);
1755         }
1756         
1757         if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1758                                &shareinfo) == FALSE) {
1759                 SetLastError (ERROR_SHARING_VIOLATION);
1760                 g_free (filename);
1761                 return FALSE;
1762         }
1763         if (shareinfo)
1764                 _wapi_handle_share_release (shareinfo);
1765 #endif
1766
1767         retval = _wapi_unlink (filename);
1768         
1769         if (retval == -1) {
1770                 _wapi_set_last_path_error_from_errno (NULL, filename);
1771         } else {
1772                 ret = TRUE;
1773         }
1774
1775         g_free(filename);
1776
1777         return(ret);
1778 }
1779
1780 /**
1781  * MoveFile:
1782  * @name: a pointer to a NULL-terminated unicode string, that names
1783  * the file to be moved.
1784  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1785  * new name for the file.
1786  *
1787  * Renames file @name to @dest_name.
1788  * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1789  * when it is the same file as the source.  In that case it silently succeeds.
1790  *
1791  * Return value: %TRUE on success, %FALSE otherwise.
1792  */
1793 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1794 {
1795         gchar *utf8_name, *utf8_dest_name;
1796         int result, errno_copy;
1797         struct stat stat_src, stat_dest;
1798         gboolean ret = FALSE;
1799         struct _WapiFileShare *shareinfo;
1800         
1801         if(name==NULL) {
1802 #ifdef DEBUG
1803                 g_message("%s: name is NULL", __func__);
1804 #endif
1805
1806                 SetLastError (ERROR_INVALID_NAME);
1807                 return(FALSE);
1808         }
1809
1810         utf8_name = mono_unicode_to_external (name);
1811         if (utf8_name == NULL) {
1812 #ifdef DEBUG
1813                 g_message ("%s: unicode conversion returned NULL", __func__);
1814 #endif
1815                 
1816                 SetLastError (ERROR_INVALID_NAME);
1817                 return FALSE;
1818         }
1819         
1820         if(dest_name==NULL) {
1821 #ifdef DEBUG
1822                 g_message("%s: name is NULL", __func__);
1823 #endif
1824
1825                 g_free (utf8_name);
1826                 SetLastError (ERROR_INVALID_NAME);
1827                 return(FALSE);
1828         }
1829
1830         utf8_dest_name = mono_unicode_to_external (dest_name);
1831         if (utf8_dest_name == NULL) {
1832 #ifdef DEBUG
1833                 g_message ("%s: unicode conversion returned NULL", __func__);
1834 #endif
1835
1836                 g_free (utf8_name);
1837                 SetLastError (ERROR_INVALID_NAME);
1838                 return FALSE;
1839         }
1840
1841         /*
1842          * In C# land we check for the existence of src, but not for dest.
1843          * We check it here and return the failure if dest exists and is not
1844          * the same file as src.
1845          */
1846         if (_wapi_stat (utf8_name, &stat_src) < 0) {
1847                 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1848                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1849                         g_free (utf8_name);
1850                         g_free (utf8_dest_name);
1851                         return FALSE;
1852                 }
1853         }
1854         
1855         if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1856                 if (stat_dest.st_dev != stat_src.st_dev ||
1857                     stat_dest.st_ino != stat_src.st_ino) {
1858                         g_free (utf8_name);
1859                         g_free (utf8_dest_name);
1860                         SetLastError (ERROR_ALREADY_EXISTS);
1861                         return FALSE;
1862                 }
1863         }
1864
1865         /* Check to make sure sharing allows us to open the file for
1866          * writing.  See bug 377049.
1867          *
1868          * Do the checks that don't need an open file descriptor, for
1869          * simplicity's sake.  If we really have to do the full checks
1870          * then we can implement that later.
1871          */
1872         if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1873                                &shareinfo) == FALSE) {
1874                 SetLastError (ERROR_SHARING_VIOLATION);
1875                 return FALSE;
1876         }
1877         if (shareinfo)
1878                 _wapi_handle_share_release (shareinfo);
1879
1880         result = _wapi_rename (utf8_name, utf8_dest_name);
1881         errno_copy = errno;
1882         
1883         if (result == -1) {
1884                 switch(errno_copy) {
1885                 case EEXIST:
1886                         SetLastError (ERROR_ALREADY_EXISTS);
1887                         break;
1888
1889                 case EXDEV:
1890                         /* Ignore here, it is dealt with below */
1891                         break;
1892                         
1893                 default:
1894                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1895                 }
1896         }
1897         
1898         g_free (utf8_name);
1899         g_free (utf8_dest_name);
1900
1901         if (result != 0 && errno_copy == EXDEV) {
1902                 if (S_ISDIR (stat_src.st_mode)) {
1903                         SetLastError (ERROR_NOT_SAME_DEVICE);
1904                         return FALSE;
1905                 }
1906                 /* Try a copy to the new location, and delete the source */
1907                 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1908                         /* CopyFile will set the error */
1909                         return(FALSE);
1910                 }
1911                 
1912                 return(DeleteFile (name));
1913         }
1914
1915         if (result == 0) {
1916                 ret = TRUE;
1917         }
1918
1919         return(ret);
1920 }
1921
1922 static gboolean
1923 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1924 {
1925         int remain, n;
1926         char *buf, *wbuf;
1927         int buf_size = st_src->st_blksize;
1928
1929         buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1930         buf = (char *) malloc (buf_size);
1931
1932         for (;;) {
1933                 remain = read (src_fd, buf, buf_size);
1934                 if (remain < 0) {
1935                         if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1936                                 continue;
1937
1938                         if (report_errors)
1939                                 _wapi_set_last_error_from_errno ();
1940
1941                         free (buf);
1942                         return FALSE;
1943                 }
1944                 if (remain == 0) {
1945                         break;
1946                 }
1947
1948                 wbuf = buf;
1949                 while (remain > 0) {
1950                         if ((n = write (dest_fd, wbuf, remain)) < 0) {
1951                                 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1952                                         continue;
1953
1954                                 if (report_errors)
1955                                         _wapi_set_last_error_from_errno ();
1956 #ifdef DEBUG
1957                                 g_message ("%s: write failed.", __func__);
1958 #endif
1959                                 free (buf);
1960                                 return FALSE;
1961                         }
1962
1963                         remain -= n;
1964                         wbuf += n;
1965                 }
1966         }
1967
1968         free (buf);
1969         return TRUE ;
1970 }
1971
1972 /**
1973  * CopyFile:
1974  * @name: a pointer to a NULL-terminated unicode string, that names
1975  * the file to be copied.
1976  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1977  * new name for the file.
1978  * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1979  *
1980  * Copies file @name to @dest_name
1981  *
1982  * Return value: %TRUE on success, %FALSE otherwise.
1983  */
1984 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1985                    gboolean fail_if_exists)
1986 {
1987         gchar *utf8_src, *utf8_dest;
1988         int src_fd, dest_fd;
1989         struct stat st, dest_st;
1990         gboolean ret = TRUE;
1991         
1992         if(name==NULL) {
1993 #ifdef DEBUG
1994                 g_message("%s: name is NULL", __func__);
1995 #endif
1996
1997                 SetLastError (ERROR_INVALID_NAME);
1998                 return(FALSE);
1999         }
2000         
2001         utf8_src = mono_unicode_to_external (name);
2002         if (utf8_src == NULL) {
2003 #ifdef DEBUG
2004                 g_message ("%s: unicode conversion of source returned NULL",
2005                            __func__);
2006 #endif
2007
2008                 SetLastError (ERROR_INVALID_PARAMETER);
2009                 return(FALSE);
2010         }
2011         
2012         if(dest_name==NULL) {
2013 #ifdef DEBUG
2014                 g_message("%s: dest is NULL", __func__);
2015 #endif
2016
2017                 g_free (utf8_src);
2018                 SetLastError (ERROR_INVALID_NAME);
2019                 return(FALSE);
2020         }
2021         
2022         utf8_dest = mono_unicode_to_external (dest_name);
2023         if (utf8_dest == NULL) {
2024 #ifdef DEBUG
2025                 g_message ("%s: unicode conversion of dest returned NULL",
2026                            __func__);
2027 #endif
2028
2029                 SetLastError (ERROR_INVALID_PARAMETER);
2030
2031                 g_free (utf8_src);
2032                 
2033                 return(FALSE);
2034         }
2035         
2036         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2037         if (src_fd < 0) {
2038                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2039                 
2040                 g_free (utf8_src);
2041                 g_free (utf8_dest);
2042                 
2043                 return(FALSE);
2044         }
2045
2046         if (fstat (src_fd, &st) < 0) {
2047                 _wapi_set_last_error_from_errno ();
2048
2049                 g_free (utf8_src);
2050                 g_free (utf8_dest);
2051                 close (src_fd);
2052                 
2053                 return(FALSE);
2054         }
2055
2056         /* Before trying to open/create the dest, we need to report a 'file busy'
2057          * error if src and dest are actually the same file. We do the check here to take
2058          * advantage of the IOMAP capability */
2059         if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev && 
2060                         st.st_ino == dest_st.st_ino) {
2061
2062                 g_free (utf8_src);
2063                 g_free (utf8_dest);
2064                 close (src_fd);
2065
2066                 SetLastError (ERROR_SHARING_VIOLATION);
2067                 return (FALSE);
2068         }
2069         
2070         if (fail_if_exists) {
2071                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2072         } else {
2073                 /* FIXME: it kinda sucks that this code path potentially scans
2074                  * the directory twice due to the weird SetLastError()
2075                  * behavior. */
2076                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2077                 if (dest_fd < 0) {
2078                         /* The file does not exist, try creating it */
2079                         dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2080                 } else {
2081                         /* Apparently this error is set if we
2082                          * overwrite the dest file
2083                          */
2084                         SetLastError (ERROR_ALREADY_EXISTS);
2085                 }
2086         }
2087         if (dest_fd < 0) {
2088                 _wapi_set_last_error_from_errno ();
2089
2090                 g_free (utf8_src);
2091                 g_free (utf8_dest);
2092                 close (src_fd);
2093
2094                 return(FALSE);
2095         }
2096
2097         if (!write_file (src_fd, dest_fd, &st, TRUE))
2098                 ret = FALSE;
2099
2100         g_free (utf8_src);
2101         g_free (utf8_dest);
2102         close (src_fd);
2103         close (dest_fd);
2104
2105         return ret;
2106 }
2107
2108 static gchar*
2109 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2110 {
2111         gchar *utf8_ret;
2112
2113         if (arg == NULL) {
2114 #ifdef DEBUG
2115                 g_message ("%s: %s is NULL", __func__, arg_name);
2116 #endif
2117                 SetLastError (ERROR_INVALID_NAME);
2118                 return NULL;
2119         }
2120
2121         utf8_ret = mono_unicode_to_external (arg);
2122         if (utf8_ret == NULL) {
2123 #ifdef DEBUG
2124                 g_message ("%s: unicode conversion of %s returned NULL",
2125                            __func__, arg_name);
2126 #endif
2127                 SetLastError (ERROR_INVALID_PARAMETER);
2128                 return NULL;
2129         }
2130
2131         return utf8_ret;
2132 }
2133
2134 gboolean
2135 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2136                       const gunichar2 *backupFileName, guint32 replaceFlags, 
2137                       gpointer exclude, gpointer reserved)
2138 {
2139         int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2140         gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2141         struct stat stBackup;
2142         gboolean ret = FALSE;
2143
2144         if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2145                 return FALSE;
2146         if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2147                 goto replace_cleanup;
2148         if (backupFileName != NULL) {
2149                 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2150                         goto replace_cleanup;
2151         }
2152
2153         if (utf8_backupFileName) {
2154                 // Open the backup file for read so we can restore the file if an error occurs.
2155                 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2156                 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2157                 errno_copy = errno;
2158                 if (result == -1)
2159                         goto replace_cleanup;
2160         }
2161
2162         result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2163         errno_copy = errno;
2164         if (result == -1) {
2165                 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2166                 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2167                 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2168                         replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2169                                                   stBackup.st_mode);
2170                         
2171                         if (replaced_fd == -1)
2172                                 goto replace_cleanup;
2173
2174                         write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2175                 }
2176
2177                 goto replace_cleanup;
2178         }
2179
2180         ret = TRUE;
2181
2182 replace_cleanup:
2183         g_free (utf8_replacedFileName);
2184         g_free (utf8_replacementFileName);
2185         g_free (utf8_backupFileName);
2186         if (backup_fd != -1)
2187                 close (backup_fd);
2188         if (replaced_fd != -1)
2189                 close (replaced_fd);
2190         return ret;
2191 }
2192
2193 /**
2194  * GetStdHandle:
2195  * @stdhandle: specifies the file descriptor
2196  *
2197  * Returns a handle for stdin, stdout, or stderr.  Always returns the
2198  * same handle for the same @stdhandle.
2199  *
2200  * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2201  */
2202
2203 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2204
2205 gpointer GetStdHandle(WapiStdHandle stdhandle)
2206 {
2207         struct _WapiHandle_file *file_handle;
2208         gpointer handle;
2209         int thr_ret, fd;
2210         const gchar *name;
2211         gboolean ok;
2212         
2213         switch(stdhandle) {
2214         case STD_INPUT_HANDLE:
2215                 fd = 0;
2216                 name = "<stdin>";
2217                 break;
2218
2219         case STD_OUTPUT_HANDLE:
2220                 fd = 1;
2221                 name = "<stdout>";
2222                 break;
2223
2224         case STD_ERROR_HANDLE:
2225                 fd = 2;
2226                 name = "<stderr>";
2227                 break;
2228
2229         default:
2230 #ifdef DEBUG
2231                 g_message("%s: unknown standard handle type", __func__);
2232 #endif
2233
2234                 SetLastError (ERROR_INVALID_PARAMETER);
2235                 return(INVALID_HANDLE_VALUE);
2236         }
2237
2238         handle = GINT_TO_POINTER (fd);
2239
2240         pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2241                               (void *)&stdhandle_mutex);
2242         thr_ret = mono_mutex_lock (&stdhandle_mutex);
2243         g_assert (thr_ret == 0);
2244
2245         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2246                                   (gpointer *)&file_handle);
2247         if (ok == FALSE) {
2248                 /* Need to create this console handle */
2249                 handle = _wapi_stdhandle_create (fd, name);
2250                 
2251                 if (handle == INVALID_HANDLE_VALUE) {
2252                         SetLastError (ERROR_NO_MORE_FILES);
2253                         goto done;
2254                 }
2255         } else {
2256                 /* Add a reference to this handle */
2257                 _wapi_handle_ref (handle);
2258         }
2259         
2260   done:
2261         thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2262         g_assert (thr_ret == 0);
2263         pthread_cleanup_pop (0);
2264         
2265         return(handle);
2266 }
2267
2268 /**
2269  * ReadFile:
2270  * @handle: The file handle to read from.  The handle must have
2271  * %GENERIC_READ access.
2272  * @buffer: The buffer to store read data in
2273  * @numbytes: The maximum number of bytes to read
2274  * @bytesread: The actual number of bytes read is stored here.  This
2275  * value can be zero if the handle is positioned at the end of the
2276  * file.
2277  * @overlapped: points to a required %WapiOverlapped structure if
2278  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2279  * otherwise.
2280  *
2281  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2282  * function reads up to @numbytes bytes from the file from the current
2283  * file position, and stores them in @buffer.  If there are not enough
2284  * bytes left in the file, just the amount available will be read.
2285  * The actual number of bytes read is stored in @bytesread.
2286
2287  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2288  * file position is ignored and the read position is taken from data
2289  * in the @overlapped structure.
2290  *
2291  * Return value: %TRUE if the read succeeds (even if no bytes were
2292  * read due to an attempt to read past the end of the file), %FALSE on
2293  * error.
2294  */
2295 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2296                   guint32 *bytesread, WapiOverlapped *overlapped)
2297 {
2298         WapiHandleType type;
2299
2300         type = _wapi_handle_type (handle);
2301         
2302         if(io_ops[type].readfile==NULL) {
2303                 SetLastError (ERROR_INVALID_HANDLE);
2304                 return(FALSE);
2305         }
2306         
2307         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2308                                       overlapped));
2309 }
2310
2311 /**
2312  * WriteFile:
2313  * @handle: The file handle to write to.  The handle must have
2314  * %GENERIC_WRITE access.
2315  * @buffer: The buffer to read data from.
2316  * @numbytes: The maximum number of bytes to write.
2317  * @byteswritten: The actual number of bytes written is stored here.
2318  * If the handle is positioned at the file end, the length of the file
2319  * is extended.  This parameter may be %NULL.
2320  * @overlapped: points to a required %WapiOverlapped structure if
2321  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2322  * otherwise.
2323  *
2324  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2325  * function writes up to @numbytes bytes from @buffer to the file at
2326  * the current file position.  If @handle is positioned at the end of
2327  * the file, the file is extended.  The actual number of bytes written
2328  * is stored in @byteswritten.
2329  *
2330  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2331  * file position is ignored and the write position is taken from data
2332  * in the @overlapped structure.
2333  *
2334  * Return value: %TRUE if the write succeeds, %FALSE on error.
2335  */
2336 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2337                    guint32 *byteswritten, WapiOverlapped *overlapped)
2338 {
2339         WapiHandleType type;
2340
2341         type = _wapi_handle_type (handle);
2342         
2343         if(io_ops[type].writefile==NULL) {
2344                 SetLastError (ERROR_INVALID_HANDLE);
2345                 return(FALSE);
2346         }
2347         
2348         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2349                                        overlapped));
2350 }
2351
2352 /**
2353  * FlushFileBuffers:
2354  * @handle: Handle to open file.  The handle must have
2355  * %GENERIC_WRITE access.
2356  *
2357  * Flushes buffers of the file and causes all unwritten data to
2358  * be written.
2359  *
2360  * Return value: %TRUE on success, %FALSE otherwise.
2361  */
2362 gboolean FlushFileBuffers(gpointer handle)
2363 {
2364         WapiHandleType type;
2365
2366         type = _wapi_handle_type (handle);
2367         
2368         if(io_ops[type].flushfile==NULL) {
2369                 SetLastError (ERROR_INVALID_HANDLE);
2370                 return(FALSE);
2371         }
2372         
2373         return(io_ops[type].flushfile (handle));
2374 }
2375
2376 /**
2377  * SetEndOfFile:
2378  * @handle: The file handle to set.  The handle must have
2379  * %GENERIC_WRITE access.
2380  *
2381  * Moves the end-of-file position to the current position of the file
2382  * pointer.  This function is used to truncate or extend a file.
2383  *
2384  * Return value: %TRUE on success, %FALSE otherwise.
2385  */
2386 gboolean SetEndOfFile(gpointer handle)
2387 {
2388         WapiHandleType type;
2389
2390         type = _wapi_handle_type (handle);
2391         
2392         if (io_ops[type].setendoffile == NULL) {
2393                 SetLastError (ERROR_INVALID_HANDLE);
2394                 return(FALSE);
2395         }
2396         
2397         return(io_ops[type].setendoffile (handle));
2398 }
2399
2400 /**
2401  * SetFilePointer:
2402  * @handle: The file handle to set.  The handle must have
2403  * %GENERIC_READ or %GENERIC_WRITE access.
2404  * @movedistance: Low 32 bits of a signed value that specifies the
2405  * number of bytes to move the file pointer.
2406  * @highmovedistance: Pointer to the high 32 bits of a signed value
2407  * that specifies the number of bytes to move the file pointer, or
2408  * %NULL.
2409  * @method: The starting point for the file pointer move.
2410  *
2411  * Sets the file pointer of an open file.
2412  *
2413  * The distance to move the file pointer is calculated from
2414  * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2415  * @movedistance is the 32-bit signed value; otherwise, @movedistance
2416  * is the low 32 bits and @highmovedistance a pointer to the high 32
2417  * bits of a 64 bit signed value.  A positive distance moves the file
2418  * pointer forward from the position specified by @method; a negative
2419  * distance moves the file pointer backward.
2420  *
2421  * If the library is compiled without large file support,
2422  * @highmovedistance is ignored and its value is set to zero on a
2423  * successful return.
2424  *
2425  * Return value: On success, the low 32 bits of the new file pointer.
2426  * If @highmovedistance is not %NULL, the high 32 bits of the new file
2427  * pointer are stored there.  On failure, %INVALID_SET_FILE_POINTER.
2428  */
2429 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2430                        gint32 *highmovedistance, WapiSeekMethod method)
2431 {
2432         WapiHandleType type;
2433
2434         type = _wapi_handle_type (handle);
2435         
2436         if (io_ops[type].seek == NULL) {
2437                 SetLastError (ERROR_INVALID_HANDLE);
2438                 return(INVALID_SET_FILE_POINTER);
2439         }
2440         
2441         return(io_ops[type].seek (handle, movedistance, highmovedistance,
2442                                   method));
2443 }
2444
2445 /**
2446  * GetFileType:
2447  * @handle: The file handle to test.
2448  *
2449  * Finds the type of file @handle.
2450  *
2451  * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2452  * unknown.  %FILE_TYPE_DISK - @handle is a disk file.
2453  * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2454  * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2455  */
2456 WapiFileType GetFileType(gpointer handle)
2457 {
2458         WapiHandleType type;
2459
2460         if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2461                 SetLastError (ERROR_INVALID_HANDLE);
2462                 return(FILE_TYPE_UNKNOWN);
2463         }
2464
2465         type = _wapi_handle_type (handle);
2466         
2467         if (io_ops[type].getfiletype == NULL) {
2468                 SetLastError (ERROR_INVALID_HANDLE);
2469                 return(FILE_TYPE_UNKNOWN);
2470         }
2471         
2472         return(io_ops[type].getfiletype ());
2473 }
2474
2475 /**
2476  * GetFileSize:
2477  * @handle: The file handle to query.  The handle must have
2478  * %GENERIC_READ or %GENERIC_WRITE access.
2479  * @highsize: If non-%NULL, the high 32 bits of the file size are
2480  * stored here.
2481  *
2482  * Retrieves the size of the file @handle.
2483  *
2484  * If the library is compiled without large file support, @highsize
2485  * has its value set to zero on a successful return.
2486  *
2487  * Return value: On success, the low 32 bits of the file size.  If
2488  * @highsize is non-%NULL then the high 32 bits of the file size are
2489  * stored here.  On failure %INVALID_FILE_SIZE is returned.
2490  */
2491 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2492 {
2493         WapiHandleType type;
2494
2495         type = _wapi_handle_type (handle);
2496         
2497         if (io_ops[type].getfilesize == NULL) {
2498                 SetLastError (ERROR_INVALID_HANDLE);
2499                 return(INVALID_FILE_SIZE);
2500         }
2501         
2502         return(io_ops[type].getfilesize (handle, highsize));
2503 }
2504
2505 /**
2506  * GetFileTime:
2507  * @handle: The file handle to query.  The handle must have
2508  * %GENERIC_READ access.
2509  * @create_time: Points to a %WapiFileTime structure to receive the
2510  * number of ticks since the epoch that file was created.  May be
2511  * %NULL.
2512  * @last_access: Points to a %WapiFileTime structure to receive the
2513  * number of ticks since the epoch when file was last accessed.  May be
2514  * %NULL.
2515  * @last_write: Points to a %WapiFileTime structure to receive the
2516  * number of ticks since the epoch when file was last written to.  May
2517  * be %NULL.
2518  *
2519  * Finds the number of ticks since the epoch that the file referenced
2520  * by @handle was created, last accessed and last modified.  A tick is
2521  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2522  * GMT.
2523  *
2524  * Create time isn't recorded on POSIX file systems or reported by
2525  * stat(2), so that time is guessed by returning the oldest of the
2526  * other times.
2527  *
2528  * Return value: %TRUE on success, %FALSE otherwise.
2529  */
2530 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2531                      WapiFileTime *last_access, WapiFileTime *last_write)
2532 {
2533         WapiHandleType type;
2534
2535         type = _wapi_handle_type (handle);
2536         
2537         if (io_ops[type].getfiletime == NULL) {
2538                 SetLastError (ERROR_INVALID_HANDLE);
2539                 return(FALSE);
2540         }
2541         
2542         return(io_ops[type].getfiletime (handle, create_time, last_access,
2543                                          last_write));
2544 }
2545
2546 /**
2547  * SetFileTime:
2548  * @handle: The file handle to set.  The handle must have
2549  * %GENERIC_WRITE access.
2550  * @create_time: Points to a %WapiFileTime structure that contains the
2551  * number of ticks since the epoch that the file was created.  May be
2552  * %NULL.
2553  * @last_access: Points to a %WapiFileTime structure that contains the
2554  * number of ticks since the epoch when the file was last accessed.
2555  * May be %NULL.
2556  * @last_write: Points to a %WapiFileTime structure that contains the
2557  * number of ticks since the epoch when the file was last written to.
2558  * May be %NULL.
2559  *
2560  * Sets the number of ticks since the epoch that the file referenced
2561  * by @handle was created, last accessed or last modified.  A tick is
2562  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2563  * GMT.
2564  *
2565  * Create time isn't recorded on POSIX file systems, and is ignored.
2566  *
2567  * Return value: %TRUE on success, %FALSE otherwise.
2568  */
2569 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2570                      const WapiFileTime *last_access,
2571                      const WapiFileTime *last_write)
2572 {
2573         WapiHandleType type;
2574
2575         type = _wapi_handle_type (handle);
2576         
2577         if (io_ops[type].setfiletime == NULL) {
2578                 SetLastError (ERROR_INVALID_HANDLE);
2579                 return(FALSE);
2580         }
2581         
2582         return(io_ops[type].setfiletime (handle, create_time, last_access,
2583                                          last_write));
2584 }
2585
2586 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
2587  * January 1 1601 GMT
2588  */
2589
2590 #define TICKS_PER_MILLISECOND 10000L
2591 #define TICKS_PER_SECOND 10000000L
2592 #define TICKS_PER_MINUTE 600000000L
2593 #define TICKS_PER_HOUR 36000000000LL
2594 #define TICKS_PER_DAY 864000000000LL
2595
2596 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2597
2598 static const guint16 mon_yday[2][13]={
2599         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2600         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2601 };
2602
2603 /**
2604  * FileTimeToSystemTime:
2605  * @file_time: Points to a %WapiFileTime structure that contains the
2606  * number of ticks to convert.
2607  * @system_time: Points to a %WapiSystemTime structure to receive the
2608  * broken-out time.
2609  *
2610  * Converts a tick count into broken-out time values.
2611  *
2612  * Return value: %TRUE on success, %FALSE otherwise.
2613  */
2614 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2615                               WapiSystemTime *system_time)
2616 {
2617         gint64 file_ticks, totaldays, rem, y;
2618         const guint16 *ip;
2619         
2620         if(system_time==NULL) {
2621 #ifdef DEBUG
2622                 g_message("%s: system_time NULL", __func__);
2623 #endif
2624
2625                 SetLastError (ERROR_INVALID_PARAMETER);
2626                 return(FALSE);
2627         }
2628         
2629         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2630                 file_time->dwLowDateTime;
2631         
2632         /* Really compares if file_ticks>=0x8000000000000000
2633          * (LLONG_MAX+1) but we're working with a signed value for the
2634          * year and day calculation to work later
2635          */
2636         if(file_ticks<0) {
2637 #ifdef DEBUG
2638                 g_message("%s: file_time too big", __func__);
2639 #endif
2640
2641                 SetLastError (ERROR_INVALID_PARAMETER);
2642                 return(FALSE);
2643         }
2644
2645         totaldays=(file_ticks / TICKS_PER_DAY);
2646         rem = file_ticks % TICKS_PER_DAY;
2647 #ifdef DEBUG
2648         g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2649 #endif
2650
2651         system_time->wHour=rem/TICKS_PER_HOUR;
2652         rem %= TICKS_PER_HOUR;
2653 #ifdef DEBUG
2654         g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2655 #endif
2656         
2657         system_time->wMinute = rem / TICKS_PER_MINUTE;
2658         rem %= TICKS_PER_MINUTE;
2659 #ifdef DEBUG
2660         g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2661                   rem);
2662 #endif
2663         
2664         system_time->wSecond = rem / TICKS_PER_SECOND;
2665         rem %= TICKS_PER_SECOND;
2666 #ifdef DEBUG
2667         g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2668                   rem);
2669 #endif
2670         
2671         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2672 #ifdef DEBUG
2673         g_message("%s: Milliseconds: %d", __func__,
2674                   system_time->wMilliseconds);
2675 #endif
2676
2677         /* January 1, 1601 was a Monday, according to Emacs calendar */
2678         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2679 #ifdef DEBUG
2680         g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2681 #endif
2682         
2683         /* This algorithm to find year and month given days from epoch
2684          * from glibc
2685          */
2686         y=1601;
2687         
2688 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2689 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2690
2691         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2692                 /* Guess a corrected year, assuming 365 days per year */
2693                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2694 #ifdef DEBUG
2695                 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2696                           totaldays, yg,
2697                           y);
2698                 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2699                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2700 #endif
2701                 
2702                 /* Adjust days and y to match the guessed year. */
2703                 totaldays -= ((yg - y) * 365
2704                               + LEAPS_THRU_END_OF (yg - 1)
2705                               - LEAPS_THRU_END_OF (y - 1));
2706 #ifdef DEBUG
2707                 g_message("%s: totaldays: %lld", __func__, totaldays);
2708 #endif
2709                 y = yg;
2710 #ifdef DEBUG
2711                 g_message("%s: y: %lld", __func__, y);
2712 #endif
2713         }
2714         
2715         system_time->wYear = y;
2716 #ifdef DEBUG
2717         g_message("%s: Year: %d", __func__, system_time->wYear);
2718 #endif
2719
2720         ip = mon_yday[isleap(y)];
2721         
2722         for(y=11; totaldays < ip[y]; --y) {
2723                 continue;
2724         }
2725         totaldays-=ip[y];
2726 #ifdef DEBUG
2727         g_message("%s: totaldays: %lld", __func__, totaldays);
2728 #endif
2729         
2730         system_time->wMonth = y + 1;
2731 #ifdef DEBUG
2732         g_message("%s: Month: %d", __func__, system_time->wMonth);
2733 #endif
2734
2735         system_time->wDay = totaldays + 1;
2736 #ifdef DEBUG
2737         g_message("%s: Day: %d", __func__, system_time->wDay);
2738 #endif
2739         
2740         return(TRUE);
2741 }
2742
2743 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2744 {
2745         struct _WapiHandle_find find_handle = {0};
2746         gpointer handle;
2747         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2748         int result;
2749         
2750         if (pattern == NULL) {
2751 #ifdef DEBUG
2752                 g_message ("%s: pattern is NULL", __func__);
2753 #endif
2754
2755                 SetLastError (ERROR_PATH_NOT_FOUND);
2756                 return(INVALID_HANDLE_VALUE);
2757         }
2758
2759         utf8_pattern = mono_unicode_to_external (pattern);
2760         if (utf8_pattern == NULL) {
2761 #ifdef DEBUG
2762                 g_message ("%s: unicode conversion returned NULL", __func__);
2763 #endif
2764                 
2765                 SetLastError (ERROR_INVALID_NAME);
2766                 return(INVALID_HANDLE_VALUE);
2767         }
2768
2769 #ifdef DEBUG
2770         g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2771 #endif
2772         
2773         /* Figure out which bit of the pattern is the directory */
2774         dir_part = _wapi_dirname (utf8_pattern);
2775         entry_part = _wapi_basename (utf8_pattern);
2776
2777 #if 0
2778         /* Don't do this check for now, it breaks if directories
2779          * really do have metachars in their names (see bug 58116).
2780          * FIXME: Figure out a better solution to keep some checks...
2781          */
2782         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2783                 SetLastError (ERROR_INVALID_NAME);
2784                 g_free (dir_part);
2785                 g_free (entry_part);
2786                 g_free (utf8_pattern);
2787                 return(INVALID_HANDLE_VALUE);
2788         }
2789 #endif
2790
2791         /* The pattern can specify a directory or a set of files.
2792          *
2793          * The pattern can have wildcard characters ? and *, but only
2794          * in the section after the last directory delimiter.  (Return
2795          * ERROR_INVALID_NAME if there are wildcards in earlier path
2796          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
2797          * means "match one character", "??" seems to mean "match one
2798          * or two characters", "???" seems to mean "match one, two or
2799          * three characters", etc.  Windows will also try and match
2800          * the mangled "short name" of files, so 8 character patterns
2801          * with wildcards will show some surprising results.
2802          *
2803          * All the written documentation I can find says that '?' 
2804          * should only match one character, and doesn't mention '??',
2805          * '???' etc.  I'm going to assume that the strict behaviour
2806          * (ie '???' means three and only three characters) is the
2807          * correct one, because that lets me use fnmatch(3) rather
2808          * than mess around with regexes.
2809          */
2810
2811         find_handle.namelist = NULL;
2812         result = _wapi_io_scandir (dir_part, entry_part,
2813                                    &find_handle.namelist);
2814         
2815         if (result == 0) {
2816                 /* No files, which windows seems to call
2817                  * FILE_NOT_FOUND
2818                  */
2819                 SetLastError (ERROR_FILE_NOT_FOUND);
2820                 g_free (utf8_pattern);
2821                 g_free (entry_part);
2822                 g_free (dir_part);
2823                 return (INVALID_HANDLE_VALUE);
2824         }
2825         
2826         if (result < 0) {
2827 #ifdef DEBUG
2828                 gint errnum = errno;
2829 #endif
2830                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2831 #ifdef DEBUG
2832                 g_message ("%s: scandir error: %s", __func__,
2833                            g_strerror (errnum));
2834 #endif
2835                 g_free (utf8_pattern);
2836                 g_free (entry_part);
2837                 g_free (dir_part);
2838                 return (INVALID_HANDLE_VALUE);
2839         }
2840
2841         g_free (utf8_pattern);
2842         g_free (entry_part);
2843         
2844 #ifdef DEBUG
2845         g_message ("%s: Got %d matches", __func__, result);
2846 #endif
2847
2848         find_handle.dir_part = dir_part;
2849         find_handle.num = result;
2850         find_handle.count = 0;
2851         
2852         handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2853         if (handle == _WAPI_HANDLE_INVALID) {
2854                 g_warning ("%s: error creating find handle", __func__);
2855                 g_free (dir_part);
2856                 g_free (entry_part);
2857                 g_free (utf8_pattern);
2858                 SetLastError (ERROR_GEN_FAILURE);
2859                 
2860                 return(INVALID_HANDLE_VALUE);
2861         }
2862
2863         if (handle != INVALID_HANDLE_VALUE &&
2864             !FindNextFile (handle, find_data)) {
2865                 FindClose (handle);
2866                 SetLastError (ERROR_NO_MORE_FILES);
2867                 handle = INVALID_HANDLE_VALUE;
2868         }
2869
2870         return (handle);
2871 }
2872
2873 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2874 {
2875         struct _WapiHandle_find *find_handle;
2876         gboolean ok;
2877         struct stat buf, linkbuf;
2878         int result;
2879         gchar *filename;
2880         gchar *utf8_filename, *utf8_basename;
2881         gunichar2 *utf16_basename;
2882         time_t create_time;
2883         glong bytes;
2884         int thr_ret;
2885         gboolean ret = FALSE;
2886         
2887         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2888                                 (gpointer *)&find_handle);
2889         if(ok==FALSE) {
2890                 g_warning ("%s: error looking up find handle %p", __func__,
2891                            handle);
2892                 SetLastError (ERROR_INVALID_HANDLE);
2893                 return(FALSE);
2894         }
2895
2896         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2897                               handle);
2898         thr_ret = _wapi_handle_lock_handle (handle);
2899         g_assert (thr_ret == 0);
2900         
2901 retry:
2902         if (find_handle->count >= find_handle->num) {
2903                 SetLastError (ERROR_NO_MORE_FILES);
2904                 goto cleanup;
2905         }
2906
2907         /* stat next match */
2908
2909         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2910
2911         result = _wapi_stat (filename, &buf);
2912         if (result == -1 && errno == ENOENT) {
2913                 /* Might be a dangling symlink */
2914                 result = _wapi_lstat (filename, &buf);
2915         }
2916         
2917         if (result != 0) {
2918 #ifdef DEBUG
2919                 g_message ("%s: stat failed: %s", __func__, filename);
2920 #endif
2921
2922                 g_free (filename);
2923                 goto retry;
2924         }
2925
2926         result = _wapi_lstat (filename, &linkbuf);
2927         if (result != 0) {
2928 #ifdef DEBUG
2929                 g_message ("%s: lstat failed: %s", __func__, filename);
2930 #endif
2931
2932                 g_free (filename);
2933                 goto retry;
2934         }
2935
2936         utf8_filename = mono_utf8_from_external (filename);
2937         if (utf8_filename == NULL) {
2938                 /* We couldn't turn this filename into utf8 (eg the
2939                  * encoding of the name wasn't convertible), so just
2940                  * ignore it.
2941                  */
2942                 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2943                 
2944                 g_free (filename);
2945                 goto retry;
2946         }
2947         g_free (filename);
2948         
2949 #ifdef DEBUG
2950         g_message ("%s: Found [%s]", __func__, utf8_filename);
2951 #endif
2952         
2953         /* fill data block */
2954
2955         if (buf.st_mtime < buf.st_ctime)
2956                 create_time = buf.st_mtime;
2957         else
2958                 create_time = buf.st_ctime;
2959         
2960         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2961
2962         _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2963         _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2964         _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2965
2966         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2967                 find_data->nFileSizeHigh = 0;
2968                 find_data->nFileSizeLow = 0;
2969         } else {
2970                 find_data->nFileSizeHigh = buf.st_size >> 32;
2971                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2972         }
2973
2974         find_data->dwReserved0 = 0;
2975         find_data->dwReserved1 = 0;
2976
2977         utf8_basename = _wapi_basename (utf8_filename);
2978         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2979                                           NULL);
2980         if(utf16_basename==NULL) {
2981                 g_free (utf8_basename);
2982                 g_free (utf8_filename);
2983                 goto retry;
2984         }
2985         ret = TRUE;
2986         
2987         /* utf16 is 2 * utf8 */
2988         bytes *= 2;
2989
2990         memset (find_data->cFileName, '\0', (MAX_PATH*2));
2991
2992         /* Truncating a utf16 string like this might leave the last
2993          * char incomplete
2994          */
2995         memcpy (find_data->cFileName, utf16_basename,
2996                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2997
2998         find_data->cAlternateFileName [0] = 0;  /* not used */
2999
3000         g_free (utf8_basename);
3001         g_free (utf8_filename);
3002         g_free (utf16_basename);
3003
3004 cleanup:
3005         thr_ret = _wapi_handle_unlock_handle (handle);
3006         g_assert (thr_ret == 0);
3007         pthread_cleanup_pop (0);
3008         
3009         return(ret);
3010 }
3011
3012 /**
3013  * FindClose:
3014  * @wapi_handle: the find handle to close.
3015  *
3016  * Closes find handle @wapi_handle
3017  *
3018  * Return value: %TRUE on success, %FALSE otherwise.
3019  */
3020 gboolean FindClose (gpointer handle)
3021 {
3022         struct _WapiHandle_find *find_handle;
3023         gboolean ok;
3024         int thr_ret;
3025
3026         if (handle == NULL) {
3027                 SetLastError (ERROR_INVALID_HANDLE);
3028                 return(FALSE);
3029         }
3030         
3031         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3032                                 (gpointer *)&find_handle);
3033         if(ok==FALSE) {
3034                 g_warning ("%s: error looking up find handle %p", __func__,
3035                            handle);
3036                 SetLastError (ERROR_INVALID_HANDLE);
3037                 return(FALSE);
3038         }
3039
3040         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3041                               handle);
3042         thr_ret = _wapi_handle_lock_handle (handle);
3043         g_assert (thr_ret == 0);
3044         
3045         g_strfreev (find_handle->namelist);
3046         g_free (find_handle->dir_part);
3047
3048         thr_ret = _wapi_handle_unlock_handle (handle);
3049         g_assert (thr_ret == 0);
3050         pthread_cleanup_pop (0);
3051         
3052         _wapi_handle_unref (handle);
3053         
3054         return(TRUE);
3055 }
3056
3057 /**
3058  * CreateDirectory:
3059  * @name: a pointer to a NULL-terminated unicode string, that names
3060  * the directory to be created.
3061  * @security: ignored for now
3062  *
3063  * Creates directory @name
3064  *
3065  * Return value: %TRUE on success, %FALSE otherwise.
3066  */
3067 gboolean CreateDirectory (const gunichar2 *name,
3068                           WapiSecurityAttributes *security)
3069 {
3070         gchar *utf8_name;
3071         int result;
3072         
3073         if (name == NULL) {
3074 #ifdef DEBUG
3075                 g_message("%s: name is NULL", __func__);
3076 #endif
3077
3078                 SetLastError (ERROR_INVALID_NAME);
3079                 return(FALSE);
3080         }
3081         
3082         utf8_name = mono_unicode_to_external (name);
3083         if (utf8_name == NULL) {
3084 #ifdef DEBUG
3085                 g_message ("%s: unicode conversion returned NULL", __func__);
3086 #endif
3087         
3088                 SetLastError (ERROR_INVALID_NAME);
3089                 return FALSE;
3090         }
3091
3092         result = _wapi_mkdir (utf8_name, 0777);
3093
3094         if (result == 0) {
3095                 g_free (utf8_name);
3096                 return TRUE;
3097         }
3098
3099         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3100         g_free (utf8_name);
3101         return FALSE;
3102 }
3103
3104 /**
3105  * RemoveDirectory:
3106  * @name: a pointer to a NULL-terminated unicode string, that names
3107  * the directory to be removed.
3108  *
3109  * Removes directory @name
3110  *
3111  * Return value: %TRUE on success, %FALSE otherwise.
3112  */
3113 gboolean RemoveDirectory (const gunichar2 *name)
3114 {
3115         gchar *utf8_name;
3116         int result;
3117         
3118         if (name == NULL) {
3119 #ifdef DEBUG
3120                 g_message("%s: name is NULL", __func__);
3121 #endif
3122
3123                 SetLastError (ERROR_INVALID_NAME);
3124                 return(FALSE);
3125         }
3126
3127         utf8_name = mono_unicode_to_external (name);
3128         if (utf8_name == NULL) {
3129 #ifdef DEBUG
3130                 g_message ("%s: unicode conversion returned NULL", __func__);
3131 #endif
3132                 
3133                 SetLastError (ERROR_INVALID_NAME);
3134                 return FALSE;
3135         }
3136
3137         result = _wapi_rmdir (utf8_name);
3138         if (result == -1) {
3139                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3140                 g_free (utf8_name);
3141                 
3142                 return(FALSE);
3143         }
3144         g_free (utf8_name);
3145
3146         return(TRUE);
3147 }
3148
3149 /**
3150  * GetFileAttributes:
3151  * @name: a pointer to a NULL-terminated unicode filename.
3152  *
3153  * Gets the attributes for @name;
3154  *
3155  * Return value: %INVALID_FILE_ATTRIBUTES on failure
3156  */
3157 guint32 GetFileAttributes (const gunichar2 *name)
3158 {
3159         gchar *utf8_name;
3160         struct stat buf, linkbuf;
3161         int result;
3162         guint32 ret;
3163         
3164         if (name == NULL) {
3165 #ifdef DEBUG
3166                 g_message("%s: name is NULL", __func__);
3167 #endif
3168
3169                 SetLastError (ERROR_INVALID_NAME);
3170                 return(FALSE);
3171         }
3172         
3173         utf8_name = mono_unicode_to_external (name);
3174         if (utf8_name == NULL) {
3175 #ifdef DEBUG
3176                 g_message ("%s: unicode conversion returned NULL", __func__);
3177 #endif
3178
3179                 SetLastError (ERROR_INVALID_PARAMETER);
3180                 return (INVALID_FILE_ATTRIBUTES);
3181         }
3182
3183         result = _wapi_stat (utf8_name, &buf);
3184         if (result == -1 && errno == ENOENT) {
3185                 /* Might be a dangling symlink... */
3186                 result = _wapi_lstat (utf8_name, &buf);
3187         }
3188
3189         if (result != 0) {
3190                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3191                 g_free (utf8_name);
3192                 return (INVALID_FILE_ATTRIBUTES);
3193         }
3194
3195         result = _wapi_lstat (utf8_name, &linkbuf);
3196         if (result != 0) {
3197                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3198                 g_free (utf8_name);
3199                 return (INVALID_FILE_ATTRIBUTES);
3200         }
3201         
3202         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3203         
3204         g_free (utf8_name);
3205
3206         return(ret);
3207 }
3208
3209 /**
3210  * GetFileAttributesEx:
3211  * @name: a pointer to a NULL-terminated unicode filename.
3212  * @level: must be GetFileExInfoStandard
3213  * @info: pointer to a WapiFileAttributesData structure
3214  *
3215  * Gets attributes, size and filetimes for @name;
3216  *
3217  * Return value: %TRUE on success, %FALSE on failure
3218  */
3219 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3220 {
3221         gchar *utf8_name;
3222         WapiFileAttributesData *data;
3223
3224         struct stat buf, linkbuf;
3225         time_t create_time;
3226         int result;
3227         
3228         if (level != GetFileExInfoStandard) {
3229 #ifdef DEBUG
3230                 g_message ("%s: info level %d not supported.", __func__,
3231                            level);
3232 #endif
3233
3234                 SetLastError (ERROR_INVALID_PARAMETER);
3235                 return FALSE;
3236         }
3237         
3238         if (name == NULL) {
3239 #ifdef DEBUG
3240                 g_message("%s: name is NULL", __func__);
3241 #endif
3242
3243                 SetLastError (ERROR_INVALID_NAME);
3244                 return(FALSE);
3245         }
3246
3247         utf8_name = mono_unicode_to_external (name);
3248         if (utf8_name == NULL) {
3249 #ifdef DEBUG
3250                 g_message ("%s: unicode conversion returned NULL", __func__);
3251 #endif
3252
3253                 SetLastError (ERROR_INVALID_PARAMETER);
3254                 return FALSE;
3255         }
3256
3257         result = _wapi_stat (utf8_name, &buf);
3258         if (result == -1 && errno == ENOENT) {
3259                 /* Might be a dangling symlink... */
3260                 result = _wapi_lstat (utf8_name, &buf);
3261         }
3262         
3263         if (result != 0) {
3264                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3265                 g_free (utf8_name);
3266                 return FALSE;
3267         }
3268
3269         result = _wapi_lstat (utf8_name, &linkbuf);
3270         if (result != 0) {
3271                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3272                 g_free (utf8_name);
3273                 return(FALSE);
3274         }
3275
3276         /* fill data block */
3277
3278         data = (WapiFileAttributesData *)info;
3279
3280         if (buf.st_mtime < buf.st_ctime)
3281                 create_time = buf.st_mtime;
3282         else
3283                 create_time = buf.st_ctime;
3284         
3285         data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3286                                                                 &buf,
3287                                                                 &linkbuf);
3288
3289         g_free (utf8_name);
3290
3291         _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3292         _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3293         _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3294
3295         if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3296                 data->nFileSizeHigh = 0;
3297                 data->nFileSizeLow = 0;
3298         }
3299         else {
3300                 data->nFileSizeHigh = buf.st_size >> 32;
3301                 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3302         }
3303
3304         return TRUE;
3305 }
3306
3307 /**
3308  * SetFileAttributes
3309  * @name: name of file
3310  * @attrs: attributes to set
3311  *
3312  * Changes the attributes on a named file.
3313  *
3314  * Return value: %TRUE on success, %FALSE on failure.
3315  */
3316 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3317 {
3318         /* FIXME: think of something clever to do on unix */
3319         gchar *utf8_name;
3320         struct stat buf;
3321         int result;
3322
3323         /*
3324          * Currently we only handle one *internal* case, with a value that is
3325          * not standard: 0x80000000, which means `set executable bit'
3326          */
3327         
3328         if (name == NULL) {
3329 #ifdef DEBUG
3330                 g_message("%s: name is NULL", __func__);
3331 #endif
3332
3333                 SetLastError (ERROR_INVALID_NAME);
3334                 return(FALSE);
3335         }
3336
3337         utf8_name = mono_unicode_to_external (name);
3338         if (utf8_name == NULL) {
3339 #ifdef DEBUG
3340                 g_message ("%s: unicode conversion returned NULL", __func__);
3341 #endif
3342
3343                 SetLastError (ERROR_INVALID_NAME);
3344                 return FALSE;
3345         }
3346
3347         result = _wapi_stat (utf8_name, &buf);
3348         if (result != 0) {
3349                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3350                 g_free (utf8_name);
3351                 return FALSE;
3352         }
3353
3354         /* Contrary to the documentation, ms allows NORMAL to be
3355          * specified along with other attributes, so dont bother to
3356          * catch that case here.
3357          */
3358         if (attrs & FILE_ATTRIBUTE_READONLY) {
3359                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3360         } else {
3361                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3362         }
3363
3364         /* Ignore the other attributes for now */
3365
3366         if (attrs & 0x80000000){
3367                 mode_t exec_mask = 0;
3368
3369                 if ((buf.st_mode & S_IRUSR) != 0)
3370                         exec_mask |= S_IXUSR;
3371
3372                 if ((buf.st_mode & S_IRGRP) != 0)
3373                         exec_mask |= S_IXGRP;
3374
3375                 if ((buf.st_mode & S_IROTH) != 0)
3376                         exec_mask |= S_IXOTH;
3377
3378                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3379         }
3380         /* Don't bother to reset executable (might need to change this
3381          * policy)
3382          */
3383         
3384         g_free (utf8_name);
3385
3386         return(TRUE);
3387 }
3388
3389 /**
3390  * GetCurrentDirectory
3391  * @length: size of the buffer
3392  * @buffer: pointer to buffer that recieves path
3393  *
3394  * Retrieves the current directory for the current process.
3395  *
3396  * Return value: number of characters in buffer on success, zero on failure
3397  */
3398 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3399 {
3400         gunichar2 *utf16_path;
3401         glong count;
3402         gsize bytes;
3403
3404         if (getcwd ((char*)buffer, length) == NULL) {
3405                 if (errno == ERANGE) { /*buffer length is not big enough */ 
3406                         gchar *path = g_get_current_dir (); /*FIXME g_get_current_dir doesn't work with broken paths and calling it just to know the path length is silly*/
3407                         if (path == NULL)
3408                                 return 0;
3409                         utf16_path = mono_unicode_from_external (path, &bytes);
3410                         g_free (utf16_path);
3411                         g_free (path);
3412                         return (bytes/2)+1;
3413                 }
3414                 _wapi_set_last_error_from_errno ();
3415                 return 0;
3416         }
3417
3418         utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3419         count = (bytes/2)+1;
3420         g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3421
3422         /* Add the terminator */
3423         memset (buffer, '\0', bytes+2);
3424         memcpy (buffer, utf16_path, bytes);
3425         
3426         g_free (utf16_path);
3427
3428         return count;
3429 }
3430
3431 /**
3432  * SetCurrentDirectory
3433  * @path: path to new directory
3434  *
3435  * Changes the directory path for the current process.
3436  *
3437  * Return value: %TRUE on success, %FALSE on failure.
3438  */
3439 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3440 {
3441         gchar *utf8_path;
3442         gboolean result;
3443
3444         if (path == NULL) {
3445                 SetLastError (ERROR_INVALID_PARAMETER);
3446                 return(FALSE);
3447         }
3448         
3449         utf8_path = mono_unicode_to_external (path);
3450         if (_wapi_chdir (utf8_path) != 0) {
3451                 _wapi_set_last_error_from_errno ();
3452                 result = FALSE;
3453         }
3454         else
3455                 result = TRUE;
3456
3457         g_free (utf8_path);
3458         return result;
3459 }
3460
3461 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3462                      WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3463 {
3464         struct _WapiHandle_file pipe_read_handle = {0};
3465         struct _WapiHandle_file pipe_write_handle = {0};
3466         gpointer read_handle;
3467         gpointer write_handle;
3468         int filedes[2];
3469         int ret;
3470         
3471         mono_once (&io_ops_once, io_ops_init);
3472         
3473 #ifdef DEBUG
3474         g_message ("%s: Creating pipe", __func__);
3475 #endif
3476
3477         ret=pipe (filedes);
3478         if(ret==-1) {
3479 #ifdef DEBUG
3480                 g_message ("%s: Error creating pipe: %s", __func__,
3481                            strerror (errno));
3482 #endif
3483                 
3484                 _wapi_set_last_error_from_errno ();
3485                 return(FALSE);
3486         }
3487
3488         if (filedes[0] >= _wapi_fd_reserve ||
3489             filedes[1] >= _wapi_fd_reserve) {
3490 #ifdef DEBUG
3491                 g_message ("%s: File descriptor is too big", __func__);
3492 #endif
3493
3494                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3495                 
3496                 close (filedes[0]);
3497                 close (filedes[1]);
3498                 
3499                 return(FALSE);
3500         }
3501         
3502         /* filedes[0] is open for reading, filedes[1] for writing */
3503
3504         pipe_read_handle.fileaccess = GENERIC_READ;
3505         read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3506                                            &pipe_read_handle);
3507         if (read_handle == _WAPI_HANDLE_INVALID) {
3508                 g_warning ("%s: error creating pipe read handle", __func__);
3509                 close (filedes[0]);
3510                 close (filedes[1]);
3511                 SetLastError (ERROR_GEN_FAILURE);
3512                 
3513                 return(FALSE);
3514         }
3515         
3516         pipe_write_handle.fileaccess = GENERIC_WRITE;
3517         write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3518                                             &pipe_write_handle);
3519         if (write_handle == _WAPI_HANDLE_INVALID) {
3520                 g_warning ("%s: error creating pipe write handle", __func__);
3521                 _wapi_handle_unref (read_handle);
3522                 
3523                 close (filedes[0]);
3524                 close (filedes[1]);
3525                 SetLastError (ERROR_GEN_FAILURE);
3526                 
3527                 return(FALSE);
3528         }
3529         
3530         *readpipe = read_handle;
3531         *writepipe = write_handle;
3532
3533 #ifdef DEBUG
3534         g_message ("%s: Returning pipe: read handle %p, write handle %p",
3535                    __func__, read_handle, write_handle);
3536 #endif
3537
3538         return(TRUE);
3539 }
3540
3541 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3542 {
3543         gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3544         gunichar2 *tmpdir16=NULL;
3545         glong dirlen;
3546         gsize bytes;
3547         guint32 ret;
3548         
3549         if(tmpdir[strlen (tmpdir)]!='/') {
3550                 g_free (tmpdir);
3551                 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3552         }
3553         
3554         tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3555         if(tmpdir16==NULL) {
3556                 g_free (tmpdir);
3557                 return(0);
3558         } else {
3559                 dirlen=(bytes/2);
3560                 
3561                 if(dirlen+1>len) {
3562 #ifdef DEBUG
3563                         g_message ("%s: Size %d smaller than needed (%ld)",
3564                                    __func__, len, dirlen+1);
3565 #endif
3566                 
3567                         ret=dirlen+1;
3568                 } else {
3569                         /* Add the terminator */
3570                         memset (buf, '\0', bytes+2);
3571                         memcpy (buf, tmpdir16, bytes);
3572                 
3573                         ret=dirlen;
3574                 }
3575         }
3576
3577         if(tmpdir16!=NULL) {
3578                 g_free (tmpdir16);
3579         }
3580         g_free (tmpdir);
3581         
3582         return(ret);
3583 }
3584
3585 #ifdef HAVE_GETFSSTAT
3586 /* Darwin has getfsstat */
3587 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3588 {
3589         struct statfs *stats;
3590         int size, n, i;
3591         gunichar2 *dir;
3592         glong length, total = 0;
3593         
3594         n = getfsstat (NULL, 0, MNT_NOWAIT);
3595         if (n == -1)
3596                 return 0;
3597         size = n * sizeof (struct statfs);
3598         stats = (struct statfs *) g_malloc (size);
3599         if (stats == NULL)
3600                 return 0;
3601         if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3602                 g_free (stats);
3603                 return 0;
3604         }
3605         for (i = 0; i < n; i++){
3606                 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3607                 if (total + length < len){
3608                         memcpy (buf + total, dir, sizeof (gunichar2) * length);
3609                         buf [total+length] = 0;
3610                 } 
3611                 g_free (dir);
3612                 total += length + 1;
3613         }
3614         if (total < len)
3615                 buf [total] = 0;
3616         total++;
3617         g_free (stats);
3618         return total;
3619 }
3620 #else
3621 /* In-place octal sequence replacement */
3622 static void
3623 unescape_octal (gchar *str)
3624 {
3625         gchar *rptr;
3626         gchar *wptr;
3627
3628         if (str == NULL)
3629                 return;
3630
3631         rptr = wptr = str;
3632         while (*rptr != '\0') {
3633                 if (*rptr == '\\') {
3634                         char c;
3635                         rptr++;
3636                         c = (*(rptr++) - '0') << 6;
3637                         c += (*(rptr++) - '0') << 3;
3638                         c += *(rptr++) - '0';
3639                         *wptr++ = c;
3640                 } else if (wptr != rptr) {
3641                         *wptr++ = *rptr++;
3642                 } else {
3643                         rptr++; wptr++;
3644                 }
3645         }
3646         *wptr = '\0';
3647 }
3648 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3649
3650 #if __linux__
3651 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3652 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3653 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3654
3655 typedef struct 
3656 {
3657         glong total;
3658         guint32 buffer_index;
3659         guint32 mountpoint_index;
3660         guint32 field_number;
3661         guint32 allocated_size;
3662         guint32 fsname_index;
3663         guint32 fstype_index;
3664         gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3665         gchar *mountpoint_allocated;
3666         gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3667         gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3668         gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3669         ssize_t nbytes;
3670         gchar delimiter;
3671         gboolean check_mount_source;
3672 } LinuxMountInfoParseState;
3673
3674 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3675 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3676 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3677 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3678
3679 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3680 {
3681         int fd;
3682         gint32 ret = 0;
3683         LinuxMountInfoParseState state;
3684         gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3685
3686         memset (buf, 0, len * sizeof (gunichar2));
3687         fd = open ("/proc/self/mountinfo", O_RDONLY);
3688         if (fd != -1)
3689                 parser = GetLogicalDriveStrings_MountInfo;
3690         else {
3691                 fd = open ("/proc/mounts", O_RDONLY);
3692                 if (fd != -1)
3693                         parser = GetLogicalDriveStrings_Mounts;
3694         }
3695
3696         if (!parser) {
3697                 ret = GetLogicalDriveStrings_Mtab (len, buf);
3698                 goto done_and_out;
3699         }
3700
3701         memset (&state, 0, sizeof (LinuxMountInfoParseState));
3702         state.field_number = 1;
3703         state.delimiter = ' ';
3704
3705         while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3706                 state.buffer_index = 0;
3707
3708                 while ((*parser)(len, buf, &state)) {
3709                         if (state.buffer [state.buffer_index] == '\n') {
3710                                 gboolean quit = add_drive_string (len, buf, &state);
3711                                 state.field_number = 1;
3712                                 state.buffer_index++;
3713                                 if (state.mountpoint_allocated) {
3714                                         g_free (state.mountpoint_allocated);
3715                                         state.mountpoint_allocated = NULL;
3716                                 }
3717                                 if (quit) {
3718                                         ret = state.total;
3719                                         goto done_and_out;
3720                                 }
3721                         }
3722                 }
3723         };
3724         ret = state.total;
3725
3726   done_and_out:
3727         if (fd != -1)
3728                 close (fd);
3729         return ret;
3730 }
3731
3732 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3733 {
3734         gchar *ptr;
3735
3736         if (state->field_number == 1)
3737                 state->check_mount_source = TRUE;
3738
3739         while (state->buffer_index < (guint32)state->nbytes) {
3740                 if (state->buffer [state->buffer_index] == state->delimiter) {
3741                         state->field_number++;
3742                         switch (state->field_number) {
3743                                 case 2:
3744                                         state->mountpoint_index = 0;
3745                                         break;
3746
3747                                 case 3:
3748                                         if (state->mountpoint_allocated)
3749                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3750                                         else
3751                                                 state->mountpoint [state->mountpoint_index] = 0;
3752                                         break;
3753
3754                                 default:
3755                                         ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3756                                         if (ptr)
3757                                                 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3758                                         else
3759                                                 state->buffer_index = state->nbytes;
3760                                         return TRUE;
3761                         }
3762                         state->buffer_index++;
3763                         continue;
3764                 } else if (state->buffer [state->buffer_index] == '\n')
3765                         return TRUE;
3766
3767                 switch (state->field_number) {
3768                         case 1:
3769                                 if (state->check_mount_source) {
3770                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3771                                                 /* We can ignore the rest, it's a device
3772                                                  * path */
3773                                                 state->check_mount_source = FALSE;
3774                                                 state->fsname [state->fsname_index++] = '/';
3775                                                 break;
3776                                         }
3777                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3778                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3779                                 }
3780                                 break;
3781
3782                         case 2:
3783                                 append_to_mountpoint (state);
3784                                 break;
3785
3786                         case 3:
3787                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3788                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3789                                 break;
3790                 }
3791
3792                 state->buffer_index++;
3793         }
3794
3795         return FALSE;
3796 }
3797
3798 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3799 {
3800         while (state->buffer_index < (guint32)state->nbytes) {
3801                 if (state->buffer [state->buffer_index] == state->delimiter) {
3802                         state->field_number++;
3803                         switch (state->field_number) {
3804                                 case 5:
3805                                         state->mountpoint_index = 0;
3806                                         break;
3807
3808                                 case 6:
3809                                         if (state->mountpoint_allocated)
3810                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3811                                         else
3812                                                 state->mountpoint [state->mountpoint_index] = 0;
3813                                         break;
3814
3815                                 case 7:
3816                                         state->delimiter = '-';
3817                                         break;
3818
3819                                 case 8:
3820                                         state->delimiter = ' ';
3821                                         break;
3822
3823                                 case 10:
3824                                         state->check_mount_source = TRUE;
3825                                         break;
3826                         }
3827                         state->buffer_index++;
3828                         continue;
3829                 } else if (state->buffer [state->buffer_index] == '\n')
3830                         return TRUE;
3831
3832                 switch (state->field_number) {
3833                         case 5:
3834                                 append_to_mountpoint (state);
3835                                 break;
3836
3837                         case 9:
3838                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3839                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3840                                 break;
3841
3842                         case 10:
3843                                 if (state->check_mount_source) {
3844                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3845                                                 /* We can ignore the rest, it's a device
3846                                                  * path */
3847                                                 state->check_mount_source = FALSE;
3848                                                 state->fsname [state->fsname_index++] = '/';
3849                                                 break;
3850                                         }
3851                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3852                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3853                                 }
3854                                 break;
3855                 }
3856
3857                 state->buffer_index++;
3858         }
3859
3860         return FALSE;
3861 }
3862
3863 static void
3864 append_to_mountpoint (LinuxMountInfoParseState *state)
3865 {
3866         gchar ch = state->buffer [state->buffer_index];
3867         if (state->mountpoint_allocated) {
3868                 if (state->mountpoint_index >= state->allocated_size) {
3869                         guint32 newsize = (state->allocated_size << 1) + 1;
3870                         gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3871
3872                         memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3873                         g_free (state->mountpoint_allocated);
3874                         state->mountpoint_allocated = newbuf;
3875                         state->allocated_size = newsize;
3876                 }
3877                 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3878         } else {
3879                 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3880                         state->allocated_size = (state->mountpoint_index << 1) + 1;
3881                         state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3882                         memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3883                         state->mountpoint_allocated [state->mountpoint_index++] = ch;
3884                 } else
3885                         state->mountpoint [state->mountpoint_index++] = ch;
3886         }
3887 }
3888
3889 static gboolean
3890 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3891 {
3892         gboolean quit = FALSE;
3893         gboolean ignore_entry;
3894
3895         if (state->fsname_index == 1 && state->fsname [0] == '/')
3896                 ignore_entry = FALSE;
3897         else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3898                 ignore_entry = TRUE;
3899         else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3900                 /* Ignore GNOME's gvfs */
3901                 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3902                         ignore_entry = TRUE;
3903                 else
3904                         ignore_entry = FALSE;
3905         } else
3906                 ignore_entry = TRUE;
3907
3908         if (!ignore_entry) {
3909                 gunichar2 *dir;
3910                 glong length;
3911                 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3912
3913                 unescape_octal (mountpoint);
3914                 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3915                 if (state->total + length + 1 > len) {
3916                         quit = TRUE;
3917                         state->total = len * 2;
3918                 } else {
3919                         length++;
3920                         memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3921                         state->total += length;
3922                 }
3923                 g_free (dir);
3924         }
3925         state->fsname_index = 0;
3926         state->fstype_index = 0;
3927
3928         return quit;
3929 }
3930 #else
3931 gint32
3932 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3933 {
3934         return GetLogicalDriveStrings_Mtab (len, buf);
3935 }
3936 #endif
3937 static gint32
3938 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3939 {
3940         FILE *fp;
3941         gunichar2 *ptr, *dir;
3942         glong length, total = 0;
3943         gchar buffer [512];
3944         gchar **splitted;
3945
3946         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
3947         buf [0] = '/';
3948         buf [1] = 0;
3949         buf [2] = 0;
3950
3951         /* Sigh, mntent and friends don't work well.
3952          * It stops on the first line that doesn't begin with a '/'.
3953          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3954         fp = fopen ("/etc/mtab", "rt");
3955         if (fp == NULL) {
3956                 fp = fopen ("/etc/mnttab", "rt");
3957                 if (fp == NULL)
3958                         return 1;
3959         }
3960
3961         ptr = buf;
3962         while (fgets (buffer, 512, fp) != NULL) {
3963                 if (*buffer != '/')
3964                         continue;
3965
3966                 splitted = g_strsplit (buffer, " ", 0);
3967                 if (!*splitted || !*(splitted + 1)) {
3968                         g_strfreev (splitted);
3969                         continue;
3970                 }
3971
3972                 unescape_octal (*(splitted + 1));
3973                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3974                 g_strfreev (splitted);
3975                 if (total + length + 1 > len) {
3976                         fclose (fp);
3977                         g_free (dir);
3978                         return len * 2; /* guess */
3979                 }
3980
3981                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3982                 g_free (dir);
3983                 total += length + 1;
3984         }
3985
3986         fclose (fp);
3987         return total;
3988 /* Commented out, does not work with my mtab!!! - Gonz */
3989 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3990 {
3991         FILE *fp;
3992         struct mntent *mnt;
3993         gunichar2 *ptr, *dir;
3994         glong len, total = 0;
3995         
3996
3997         fp = setmntent ("/etc/mtab", "rt");
3998         if (fp == NULL) {
3999                 fp = setmntent ("/etc/mnttab", "rt");
4000                 if (fp == NULL)
4001                         return;
4002         }
4003
4004         ptr = buf;
4005         while ((mnt = getmntent (fp)) != NULL) {
4006                 g_print ("GOT %s\n", mnt->mnt_dir);
4007                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4008                 if (total + len + 1 > len) {
4009                         return len * 2; /* guess */
4010                 }
4011
4012                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4013                 g_free (dir);
4014                 total += len + 1;
4015         }
4016
4017         endmntent (fp);
4018         return total;
4019 }
4020 #endif
4021 }
4022 #endif
4023
4024 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
4025 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4026                             WapiULargeInteger *total_number_of_bytes,
4027                             WapiULargeInteger *total_number_of_free_bytes)
4028 {
4029 #ifdef HAVE_STATVFS
4030         struct statvfs fsstat;
4031 #elif defined(HAVE_STATFS)
4032         struct statfs fsstat;
4033 #endif
4034         gboolean isreadonly;
4035         gchar *utf8_path_name;
4036         int ret;
4037         unsigned long block_size;
4038
4039         if (path_name == NULL) {
4040                 utf8_path_name = g_strdup (g_get_current_dir());
4041                 if (utf8_path_name == NULL) {
4042                         SetLastError (ERROR_DIRECTORY);
4043                         return(FALSE);
4044                 }
4045         }
4046         else {
4047                 utf8_path_name = mono_unicode_to_external (path_name);
4048                 if (utf8_path_name == NULL) {
4049 #ifdef DEBUG
4050                         g_message("%s: unicode conversion returned NULL", __func__);
4051 #endif
4052
4053                         SetLastError (ERROR_INVALID_NAME);
4054                         return(FALSE);
4055                 }
4056         }
4057
4058         do {
4059 #ifdef HAVE_STATVFS
4060                 ret = statvfs (utf8_path_name, &fsstat);
4061                 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4062                 block_size = fsstat.f_frsize;
4063 #elif defined(HAVE_STATFS)
4064                 ret = statfs (utf8_path_name, &fsstat);
4065                 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4066                 block_size = fsstat.f_bsize;
4067 #endif
4068         } while(ret == -1 && errno == EINTR);
4069
4070         g_free(utf8_path_name);
4071
4072         if (ret == -1) {
4073                 _wapi_set_last_error_from_errno ();
4074 #ifdef DEBUG
4075                 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
4076 #endif
4077                 return(FALSE);
4078         }
4079
4080         /* total number of free bytes for non-root */
4081         if (free_bytes_avail != NULL) {
4082                 if (isreadonly) {
4083                         free_bytes_avail->QuadPart = 0;
4084                 }
4085                 else {
4086                         free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4087                 }
4088         }
4089
4090         /* total number of bytes available for non-root */
4091         if (total_number_of_bytes != NULL) {
4092                 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4093         }
4094
4095         /* total number of bytes available for root */
4096         if (total_number_of_free_bytes != NULL) {
4097                 if (isreadonly) {
4098                         total_number_of_free_bytes->QuadPart = 0;
4099                 }
4100                 else {
4101                         total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4102                 }
4103         }
4104         
4105         return(TRUE);
4106 }
4107 #else
4108 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4109                             WapiULargeInteger *total_number_of_bytes,
4110                             WapiULargeInteger *total_number_of_free_bytes)
4111 {
4112         if (free_bytes_avail != NULL) {
4113                 free_bytes_avail->QuadPart = (guint64) -1;
4114         }
4115
4116         if (total_number_of_bytes != NULL) {
4117                 total_number_of_bytes->QuadPart = (guint64) -1;
4118         }
4119
4120         if (total_number_of_free_bytes != NULL) {
4121                 total_number_of_free_bytes->QuadPart = (guint64) -1;
4122         }
4123
4124         return(TRUE);
4125 }
4126 #endif
4127
4128 /*
4129  * General Unix support
4130  */
4131 typedef struct {
4132         guint32 drive_type;
4133 #if __linux__
4134         const long fstypeid;
4135 #endif
4136         const gchar* fstype;
4137 } _wapi_drive_type;
4138
4139 static _wapi_drive_type _wapi_drive_types[] = {
4140 #if PLATFORM_MACOSX
4141         { DRIVE_REMOTE, "afp" },
4142         { DRIVE_REMOTE, "autofs" },
4143         { DRIVE_CDROM, "cddafs" },
4144         { DRIVE_CDROM, "cd9660" },
4145         { DRIVE_RAMDISK, "devfs" },
4146         { DRIVE_FIXED, "exfat" },
4147         { DRIVE_RAMDISK, "fdesc" },
4148         { DRIVE_REMOTE, "ftp" },
4149         { DRIVE_FIXED, "hfs" },
4150         { DRIVE_FIXED, "msdos" },
4151         { DRIVE_REMOTE, "nfs" },
4152         { DRIVE_FIXED, "ntfs" },
4153         { DRIVE_REMOTE, "smbfs" },
4154         { DRIVE_FIXED, "udf" },
4155         { DRIVE_REMOTE, "webdav" },
4156         { DRIVE_UNKNOWN, NULL }
4157 #elif __linux__
4158         { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4159         { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4160         { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4161         { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4162         { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4163         { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4164         { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4165         { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4166         { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4167         { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4168         { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4169         { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4170         { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4171         { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4172         { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4173         { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4174         { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4175         { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4176         { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4177         { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4178         { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4179         { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4180         { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4181         { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4182         { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4183         { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4184         { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4185         { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4186         { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4187         { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4188         { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4189         { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4190         { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4191         { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4192         { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4193         { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4194         { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4195         { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4196         { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4197         { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4198         { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4199         { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4200         { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4201         { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4202         { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4203         { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4204         { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4205         { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4206         { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4207         { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4208         { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4209         { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4210         { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4211         { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4212         { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4213         { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4214         { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4215         { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4216         { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4217         { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4218         { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4219         { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4220         { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4221         { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4222         { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4223         { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4224         { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4225         { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4226         { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4227         { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4228         { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4229         { DRIVE_UNKNOWN, 0, NULL}
4230 #else
4231         { DRIVE_RAMDISK, "ramfs"      },
4232         { DRIVE_RAMDISK, "tmpfs"      },
4233         { DRIVE_RAMDISK, "proc"       },
4234         { DRIVE_RAMDISK, "sysfs"      },
4235         { DRIVE_RAMDISK, "debugfs"    },
4236         { DRIVE_RAMDISK, "devpts"     },
4237         { DRIVE_RAMDISK, "securityfs" },
4238         { DRIVE_CDROM,   "iso9660"    },
4239         { DRIVE_FIXED,   "ext2"       },
4240         { DRIVE_FIXED,   "ext3"       },
4241         { DRIVE_FIXED,   "ext4"       },
4242         { DRIVE_FIXED,   "sysv"       },
4243         { DRIVE_FIXED,   "reiserfs"   },
4244         { DRIVE_FIXED,   "ufs"        },
4245         { DRIVE_FIXED,   "vfat"       },
4246         { DRIVE_FIXED,   "msdos"      },
4247         { DRIVE_FIXED,   "udf"        },
4248         { DRIVE_FIXED,   "hfs"        },
4249         { DRIVE_FIXED,   "hpfs"       },
4250         { DRIVE_FIXED,   "qnx4"       },
4251         { DRIVE_FIXED,   "ntfs"       },
4252         { DRIVE_FIXED,   "ntfs-3g"    },
4253         { DRIVE_REMOTE,  "smbfs"      },
4254         { DRIVE_REMOTE,  "fuse"       },
4255         { DRIVE_REMOTE,  "nfs"        },
4256         { DRIVE_REMOTE,  "nfs4"       },
4257         { DRIVE_REMOTE,  "cifs"       },
4258         { DRIVE_REMOTE,  "ncpfs"      },
4259         { DRIVE_REMOTE,  "coda"       },
4260         { DRIVE_REMOTE,  "afs"        },
4261         { DRIVE_UNKNOWN, NULL         }
4262 #endif
4263 };
4264
4265 #if __linux__
4266 static guint32 _wapi_get_drive_type(long f_type)
4267 {
4268         _wapi_drive_type *current;
4269
4270         current = &_wapi_drive_types[0];
4271         while (current->drive_type != DRIVE_UNKNOWN) {
4272                 if (current->fstypeid == f_type)
4273                         return current->drive_type;
4274                 current++;
4275         }
4276
4277         return DRIVE_UNKNOWN;
4278 }
4279 #else
4280 static guint32 _wapi_get_drive_type(const gchar* fstype)
4281 {
4282         _wapi_drive_type *current;
4283
4284         current = &_wapi_drive_types[0];
4285         while (current->drive_type != DRIVE_UNKNOWN) {
4286                 if (strcmp (current->fstype, fstype) == 0)
4287                         break;
4288
4289                 current++;
4290         }
4291         
4292         return current->drive_type;
4293 }
4294 #endif
4295
4296 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4297 static guint32
4298 GetDriveTypeFromPath (const char *utf8_root_path_name)
4299 {
4300         struct statfs buf;
4301         
4302         if (statfs (utf8_root_path_name, &buf) == -1)
4303                 return DRIVE_UNKNOWN;
4304 #if PLATFORM_MACOSX
4305         return _wapi_get_drive_type (buf.f_fstypename);
4306 #else
4307         return _wapi_get_drive_type (buf.f_type);
4308 #endif
4309 }
4310 #else
4311 static guint32
4312 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4313 {
4314         guint32 drive_type;
4315         FILE *fp;
4316         gchar buffer [512];
4317         gchar **splitted;
4318
4319         fp = fopen ("/etc/mtab", "rt");
4320         if (fp == NULL) {
4321                 fp = fopen ("/etc/mnttab", "rt");
4322                 if (fp == NULL) 
4323                         return(DRIVE_UNKNOWN);
4324         }
4325
4326         drive_type = DRIVE_NO_ROOT_DIR;
4327         while (fgets (buffer, 512, fp) != NULL) {
4328                 splitted = g_strsplit (buffer, " ", 0);
4329                 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4330                         g_strfreev (splitted);
4331                         continue;
4332                 }
4333
4334                 /* compare given root_path_name with the one from mtab, 
4335                   if length of utf8_root_path_name is zero it must be the root dir */
4336                 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4337                     (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4338                         drive_type = _wapi_get_drive_type (*(splitted + 2));
4339                         g_strfreev (splitted);
4340                         break;
4341                 }
4342
4343                 g_strfreev (splitted);
4344         }
4345
4346         fclose (fp);
4347         return drive_type;
4348 }
4349 #endif
4350
4351 guint32 GetDriveType(const gunichar2 *root_path_name)
4352 {
4353         gchar *utf8_root_path_name;
4354         guint32 drive_type;
4355
4356         if (root_path_name == NULL) {
4357                 utf8_root_path_name = g_strdup (g_get_current_dir());
4358                 if (utf8_root_path_name == NULL) {
4359                         return(DRIVE_NO_ROOT_DIR);
4360                 }
4361         }
4362         else {
4363                 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4364                 if (utf8_root_path_name == NULL) {
4365 #ifdef DEBUG
4366                         g_message("%s: unicode conversion returned NULL", __func__);
4367 #endif
4368                         return(DRIVE_NO_ROOT_DIR);
4369                 }
4370                 
4371                 /* strip trailing slash for compare below */
4372                 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4373                         utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4374                 }
4375         }
4376         drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4377         g_free (utf8_root_path_name);
4378
4379         return (drive_type);
4380 }
4381
4382 static const gchar*
4383 get_fstypename (gchar *utfpath)
4384 {
4385 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4386         struct statfs stat;
4387 #if __linux__
4388         _wapi_drive_type *current;
4389 #endif
4390         if (statfs (utfpath, &stat) == -1)
4391                 return NULL;
4392 #if PLATFORM_MACOSX
4393         return stat.f_fstypename;
4394 #else
4395         current = &_wapi_drive_types[0];
4396         while (current->drive_type != DRIVE_UNKNOWN) {
4397                 if (stat.f_type == current->fstypeid)
4398                         return current->fstype;
4399                 current++;
4400         }
4401         return NULL;
4402 #endif
4403 #else
4404         return NULL;
4405 #endif
4406 }
4407
4408 /* Linux has struct statfs which has a different layout */
4409 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__)
4410 gboolean
4411 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4412 {
4413         gchar *utfpath;
4414         const gchar *fstypename;
4415         gboolean status = FALSE;
4416         glong len;
4417         
4418         // We only support getting the file system type
4419         if (fsbuffer == NULL)
4420                 return 0;
4421         
4422         utfpath = mono_unicode_to_external (path);
4423         if ((fstypename = get_fstypename (utfpath)) != NULL){
4424                 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4425                 if (ret != NULL && len < fsbuffersize){
4426                         memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4427                         fsbuffer [len] = 0;
4428                         status = TRUE;
4429                 }
4430                 if (ret != NULL)
4431                         g_free (ret);
4432         }
4433         g_free (utfpath);
4434         return status;
4435 }
4436 #endif