Merged pull request #58 from XTZGZoReX/master.
[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 (attrs & FILE_ATTRIBUTE_READONLY) {
1744 #ifdef DEBUG
1745                 g_message ("%s: file %s is readonly", __func__, filename);
1746 #endif
1747                 SetLastError (ERROR_ACCESS_DENIED);
1748                 g_free (filename);
1749                 return(FALSE);
1750         }
1751
1752 #if 0
1753         /* Check to make sure sharing allows us to open the file for
1754          * writing.  See bug 323389.
1755          *
1756          * Do the checks that don't need an open file descriptor, for
1757          * simplicity's sake.  If we really have to do the full checks
1758          * then we can implement that later.
1759          */
1760         if (_wapi_stat (filename, &statbuf) < 0) {
1761                 _wapi_set_last_path_error_from_errno (NULL, filename);
1762                 g_free (filename);
1763                 return(FALSE);
1764         }
1765         
1766         if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1767                                &shareinfo) == FALSE) {
1768                 SetLastError (ERROR_SHARING_VIOLATION);
1769                 g_free (filename);
1770                 return FALSE;
1771         }
1772         if (shareinfo)
1773                 _wapi_handle_share_release (shareinfo);
1774 #endif
1775
1776         retval = _wapi_unlink (filename);
1777         
1778         if (retval == -1) {
1779                 _wapi_set_last_path_error_from_errno (NULL, filename);
1780         } else {
1781                 ret = TRUE;
1782         }
1783
1784         g_free(filename);
1785
1786         return(ret);
1787 }
1788
1789 /**
1790  * MoveFile:
1791  * @name: a pointer to a NULL-terminated unicode string, that names
1792  * the file to be moved.
1793  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1794  * new name for the file.
1795  *
1796  * Renames file @name to @dest_name.
1797  * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1798  * when it is the same file as the source.  In that case it silently succeeds.
1799  *
1800  * Return value: %TRUE on success, %FALSE otherwise.
1801  */
1802 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1803 {
1804         gchar *utf8_name, *utf8_dest_name;
1805         int result, errno_copy;
1806         struct stat stat_src, stat_dest;
1807         gboolean ret = FALSE;
1808         struct _WapiFileShare *shareinfo;
1809         
1810         if(name==NULL) {
1811 #ifdef DEBUG
1812                 g_message("%s: name is NULL", __func__);
1813 #endif
1814
1815                 SetLastError (ERROR_INVALID_NAME);
1816                 return(FALSE);
1817         }
1818
1819         utf8_name = mono_unicode_to_external (name);
1820         if (utf8_name == NULL) {
1821 #ifdef DEBUG
1822                 g_message ("%s: unicode conversion returned NULL", __func__);
1823 #endif
1824                 
1825                 SetLastError (ERROR_INVALID_NAME);
1826                 return FALSE;
1827         }
1828         
1829         if(dest_name==NULL) {
1830 #ifdef DEBUG
1831                 g_message("%s: name is NULL", __func__);
1832 #endif
1833
1834                 g_free (utf8_name);
1835                 SetLastError (ERROR_INVALID_NAME);
1836                 return(FALSE);
1837         }
1838
1839         utf8_dest_name = mono_unicode_to_external (dest_name);
1840         if (utf8_dest_name == NULL) {
1841 #ifdef DEBUG
1842                 g_message ("%s: unicode conversion returned NULL", __func__);
1843 #endif
1844
1845                 g_free (utf8_name);
1846                 SetLastError (ERROR_INVALID_NAME);
1847                 return FALSE;
1848         }
1849
1850         /*
1851          * In C# land we check for the existence of src, but not for dest.
1852          * We check it here and return the failure if dest exists and is not
1853          * the same file as src.
1854          */
1855         if (_wapi_stat (utf8_name, &stat_src) < 0) {
1856                 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1857                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1858                         g_free (utf8_name);
1859                         g_free (utf8_dest_name);
1860                         return FALSE;
1861                 }
1862         }
1863         
1864         if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1865                 if (stat_dest.st_dev != stat_src.st_dev ||
1866                     stat_dest.st_ino != stat_src.st_ino) {
1867                         g_free (utf8_name);
1868                         g_free (utf8_dest_name);
1869                         SetLastError (ERROR_ALREADY_EXISTS);
1870                         return FALSE;
1871                 }
1872         }
1873
1874         /* Check to make sure sharing allows us to open the file for
1875          * writing.  See bug 377049.
1876          *
1877          * Do the checks that don't need an open file descriptor, for
1878          * simplicity's sake.  If we really have to do the full checks
1879          * then we can implement that later.
1880          */
1881         if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
1882                                &shareinfo) == FALSE) {
1883                 SetLastError (ERROR_SHARING_VIOLATION);
1884                 return FALSE;
1885         }
1886         if (shareinfo)
1887                 _wapi_handle_share_release (shareinfo);
1888
1889         result = _wapi_rename (utf8_name, utf8_dest_name);
1890         errno_copy = errno;
1891         
1892         if (result == -1) {
1893                 switch(errno_copy) {
1894                 case EEXIST:
1895                         SetLastError (ERROR_ALREADY_EXISTS);
1896                         break;
1897
1898                 case EXDEV:
1899                         /* Ignore here, it is dealt with below */
1900                         break;
1901                         
1902                 default:
1903                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1904                 }
1905         }
1906         
1907         g_free (utf8_name);
1908         g_free (utf8_dest_name);
1909
1910         if (result != 0 && errno_copy == EXDEV) {
1911                 if (S_ISDIR (stat_src.st_mode)) {
1912                         SetLastError (ERROR_NOT_SAME_DEVICE);
1913                         return FALSE;
1914                 }
1915                 /* Try a copy to the new location, and delete the source */
1916                 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1917                         /* CopyFile will set the error */
1918                         return(FALSE);
1919                 }
1920                 
1921                 return(DeleteFile (name));
1922         }
1923
1924         if (result == 0) {
1925                 ret = TRUE;
1926         }
1927
1928         return(ret);
1929 }
1930
1931 static gboolean
1932 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1933 {
1934         int remain, n;
1935         char *buf, *wbuf;
1936         int buf_size = st_src->st_blksize;
1937
1938         buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1939         buf = (char *) malloc (buf_size);
1940
1941         for (;;) {
1942                 remain = read (src_fd, buf, buf_size);
1943                 if (remain < 0) {
1944                         if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1945                                 continue;
1946
1947                         if (report_errors)
1948                                 _wapi_set_last_error_from_errno ();
1949
1950                         free (buf);
1951                         return FALSE;
1952                 }
1953                 if (remain == 0) {
1954                         break;
1955                 }
1956
1957                 wbuf = buf;
1958                 while (remain > 0) {
1959                         if ((n = write (dest_fd, wbuf, remain)) < 0) {
1960                                 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1961                                         continue;
1962
1963                                 if (report_errors)
1964                                         _wapi_set_last_error_from_errno ();
1965 #ifdef DEBUG
1966                                 g_message ("%s: write failed.", __func__);
1967 #endif
1968                                 free (buf);
1969                                 return FALSE;
1970                         }
1971
1972                         remain -= n;
1973                         wbuf += n;
1974                 }
1975         }
1976
1977         free (buf);
1978         return TRUE ;
1979 }
1980
1981 /**
1982  * CopyFile:
1983  * @name: a pointer to a NULL-terminated unicode string, that names
1984  * the file to be copied.
1985  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1986  * new name for the file.
1987  * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1988  *
1989  * Copies file @name to @dest_name
1990  *
1991  * Return value: %TRUE on success, %FALSE otherwise.
1992  */
1993 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1994                    gboolean fail_if_exists)
1995 {
1996         gchar *utf8_src, *utf8_dest;
1997         int src_fd, dest_fd;
1998         struct stat st, dest_st;
1999         gboolean ret = TRUE;
2000         
2001         if(name==NULL) {
2002 #ifdef DEBUG
2003                 g_message("%s: name is NULL", __func__);
2004 #endif
2005
2006                 SetLastError (ERROR_INVALID_NAME);
2007                 return(FALSE);
2008         }
2009         
2010         utf8_src = mono_unicode_to_external (name);
2011         if (utf8_src == NULL) {
2012 #ifdef DEBUG
2013                 g_message ("%s: unicode conversion of source returned NULL",
2014                            __func__);
2015 #endif
2016
2017                 SetLastError (ERROR_INVALID_PARAMETER);
2018                 return(FALSE);
2019         }
2020         
2021         if(dest_name==NULL) {
2022 #ifdef DEBUG
2023                 g_message("%s: dest is NULL", __func__);
2024 #endif
2025
2026                 g_free (utf8_src);
2027                 SetLastError (ERROR_INVALID_NAME);
2028                 return(FALSE);
2029         }
2030         
2031         utf8_dest = mono_unicode_to_external (dest_name);
2032         if (utf8_dest == NULL) {
2033 #ifdef DEBUG
2034                 g_message ("%s: unicode conversion of dest returned NULL",
2035                            __func__);
2036 #endif
2037
2038                 SetLastError (ERROR_INVALID_PARAMETER);
2039
2040                 g_free (utf8_src);
2041                 
2042                 return(FALSE);
2043         }
2044         
2045         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2046         if (src_fd < 0) {
2047                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2048                 
2049                 g_free (utf8_src);
2050                 g_free (utf8_dest);
2051                 
2052                 return(FALSE);
2053         }
2054
2055         if (fstat (src_fd, &st) < 0) {
2056                 _wapi_set_last_error_from_errno ();
2057
2058                 g_free (utf8_src);
2059                 g_free (utf8_dest);
2060                 close (src_fd);
2061                 
2062                 return(FALSE);
2063         }
2064
2065         /* Before trying to open/create the dest, we need to report a 'file busy'
2066          * error if src and dest are actually the same file. We do the check here to take
2067          * advantage of the IOMAP capability */
2068         if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev && 
2069                         st.st_ino == dest_st.st_ino) {
2070
2071                 g_free (utf8_src);
2072                 g_free (utf8_dest);
2073                 close (src_fd);
2074
2075                 SetLastError (ERROR_SHARING_VIOLATION);
2076                 return (FALSE);
2077         }
2078         
2079         if (fail_if_exists) {
2080                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2081         } else {
2082                 /* FIXME: it kinda sucks that this code path potentially scans
2083                  * the directory twice due to the weird SetLastError()
2084                  * behavior. */
2085                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2086                 if (dest_fd < 0) {
2087                         /* The file does not exist, try creating it */
2088                         dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2089                 } else {
2090                         /* Apparently this error is set if we
2091                          * overwrite the dest file
2092                          */
2093                         SetLastError (ERROR_ALREADY_EXISTS);
2094                 }
2095         }
2096         if (dest_fd < 0) {
2097                 _wapi_set_last_error_from_errno ();
2098
2099                 g_free (utf8_src);
2100                 g_free (utf8_dest);
2101                 close (src_fd);
2102
2103                 return(FALSE);
2104         }
2105
2106         if (!write_file (src_fd, dest_fd, &st, TRUE))
2107                 ret = FALSE;
2108
2109         g_free (utf8_src);
2110         g_free (utf8_dest);
2111         close (src_fd);
2112         close (dest_fd);
2113
2114         return ret;
2115 }
2116
2117 static gchar*
2118 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2119 {
2120         gchar *utf8_ret;
2121
2122         if (arg == NULL) {
2123 #ifdef DEBUG
2124                 g_message ("%s: %s is NULL", __func__, arg_name);
2125 #endif
2126                 SetLastError (ERROR_INVALID_NAME);
2127                 return NULL;
2128         }
2129
2130         utf8_ret = mono_unicode_to_external (arg);
2131         if (utf8_ret == NULL) {
2132 #ifdef DEBUG
2133                 g_message ("%s: unicode conversion of %s returned NULL",
2134                            __func__, arg_name);
2135 #endif
2136                 SetLastError (ERROR_INVALID_PARAMETER);
2137                 return NULL;
2138         }
2139
2140         return utf8_ret;
2141 }
2142
2143 gboolean
2144 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2145                       const gunichar2 *backupFileName, guint32 replaceFlags, 
2146                       gpointer exclude, gpointer reserved)
2147 {
2148         int result, errno_copy, backup_fd = -1,replaced_fd = -1;
2149         gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2150         struct stat stBackup;
2151         gboolean ret = FALSE;
2152
2153         if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2154                 return FALSE;
2155         if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2156                 goto replace_cleanup;
2157         if (backupFileName != NULL) {
2158                 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2159                         goto replace_cleanup;
2160         }
2161
2162         if (utf8_backupFileName) {
2163                 // Open the backup file for read so we can restore the file if an error occurs.
2164                 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2165                 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2166                 errno_copy = errno;
2167                 if (result == -1)
2168                         goto replace_cleanup;
2169         }
2170
2171         result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2172         errno_copy = errno;
2173         if (result == -1) {
2174                 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2175                 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2176                 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2177                         replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2178                                                   stBackup.st_mode);
2179                         
2180                         if (replaced_fd == -1)
2181                                 goto replace_cleanup;
2182
2183                         write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2184                 }
2185
2186                 goto replace_cleanup;
2187         }
2188
2189         ret = TRUE;
2190
2191 replace_cleanup:
2192         g_free (utf8_replacedFileName);
2193         g_free (utf8_replacementFileName);
2194         g_free (utf8_backupFileName);
2195         if (backup_fd != -1)
2196                 close (backup_fd);
2197         if (replaced_fd != -1)
2198                 close (replaced_fd);
2199         return ret;
2200 }
2201
2202 /**
2203  * GetStdHandle:
2204  * @stdhandle: specifies the file descriptor
2205  *
2206  * Returns a handle for stdin, stdout, or stderr.  Always returns the
2207  * same handle for the same @stdhandle.
2208  *
2209  * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2210  */
2211
2212 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2213
2214 gpointer GetStdHandle(WapiStdHandle stdhandle)
2215 {
2216         struct _WapiHandle_file *file_handle;
2217         gpointer handle;
2218         int thr_ret, fd;
2219         const gchar *name;
2220         gboolean ok;
2221         
2222         switch(stdhandle) {
2223         case STD_INPUT_HANDLE:
2224                 fd = 0;
2225                 name = "<stdin>";
2226                 break;
2227
2228         case STD_OUTPUT_HANDLE:
2229                 fd = 1;
2230                 name = "<stdout>";
2231                 break;
2232
2233         case STD_ERROR_HANDLE:
2234                 fd = 2;
2235                 name = "<stderr>";
2236                 break;
2237
2238         default:
2239 #ifdef DEBUG
2240                 g_message("%s: unknown standard handle type", __func__);
2241 #endif
2242
2243                 SetLastError (ERROR_INVALID_PARAMETER);
2244                 return(INVALID_HANDLE_VALUE);
2245         }
2246
2247         handle = GINT_TO_POINTER (fd);
2248
2249         pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2250                               (void *)&stdhandle_mutex);
2251         thr_ret = mono_mutex_lock (&stdhandle_mutex);
2252         g_assert (thr_ret == 0);
2253
2254         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2255                                   (gpointer *)&file_handle);
2256         if (ok == FALSE) {
2257                 /* Need to create this console handle */
2258                 handle = _wapi_stdhandle_create (fd, name);
2259                 
2260                 if (handle == INVALID_HANDLE_VALUE) {
2261                         SetLastError (ERROR_NO_MORE_FILES);
2262                         goto done;
2263                 }
2264         } else {
2265                 /* Add a reference to this handle */
2266                 _wapi_handle_ref (handle);
2267         }
2268         
2269   done:
2270         thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2271         g_assert (thr_ret == 0);
2272         pthread_cleanup_pop (0);
2273         
2274         return(handle);
2275 }
2276
2277 /**
2278  * ReadFile:
2279  * @handle: The file handle to read from.  The handle must have
2280  * %GENERIC_READ access.
2281  * @buffer: The buffer to store read data in
2282  * @numbytes: The maximum number of bytes to read
2283  * @bytesread: The actual number of bytes read is stored here.  This
2284  * value can be zero if the handle is positioned at the end of the
2285  * file.
2286  * @overlapped: points to a required %WapiOverlapped structure if
2287  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2288  * otherwise.
2289  *
2290  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2291  * function reads up to @numbytes bytes from the file from the current
2292  * file position, and stores them in @buffer.  If there are not enough
2293  * bytes left in the file, just the amount available will be read.
2294  * The actual number of bytes read is stored in @bytesread.
2295
2296  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2297  * file position is ignored and the read position is taken from data
2298  * in the @overlapped structure.
2299  *
2300  * Return value: %TRUE if the read succeeds (even if no bytes were
2301  * read due to an attempt to read past the end of the file), %FALSE on
2302  * error.
2303  */
2304 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2305                   guint32 *bytesread, WapiOverlapped *overlapped)
2306 {
2307         WapiHandleType type;
2308
2309         type = _wapi_handle_type (handle);
2310         
2311         if(io_ops[type].readfile==NULL) {
2312                 SetLastError (ERROR_INVALID_HANDLE);
2313                 return(FALSE);
2314         }
2315         
2316         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2317                                       overlapped));
2318 }
2319
2320 /**
2321  * WriteFile:
2322  * @handle: The file handle to write to.  The handle must have
2323  * %GENERIC_WRITE access.
2324  * @buffer: The buffer to read data from.
2325  * @numbytes: The maximum number of bytes to write.
2326  * @byteswritten: The actual number of bytes written is stored here.
2327  * If the handle is positioned at the file end, the length of the file
2328  * is extended.  This parameter may be %NULL.
2329  * @overlapped: points to a required %WapiOverlapped structure if
2330  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2331  * otherwise.
2332  *
2333  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2334  * function writes up to @numbytes bytes from @buffer to the file at
2335  * the current file position.  If @handle is positioned at the end of
2336  * the file, the file is extended.  The actual number of bytes written
2337  * is stored in @byteswritten.
2338  *
2339  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2340  * file position is ignored and the write position is taken from data
2341  * in the @overlapped structure.
2342  *
2343  * Return value: %TRUE if the write succeeds, %FALSE on error.
2344  */
2345 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2346                    guint32 *byteswritten, WapiOverlapped *overlapped)
2347 {
2348         WapiHandleType type;
2349
2350         type = _wapi_handle_type (handle);
2351         
2352         if(io_ops[type].writefile==NULL) {
2353                 SetLastError (ERROR_INVALID_HANDLE);
2354                 return(FALSE);
2355         }
2356         
2357         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2358                                        overlapped));
2359 }
2360
2361 /**
2362  * FlushFileBuffers:
2363  * @handle: Handle to open file.  The handle must have
2364  * %GENERIC_WRITE access.
2365  *
2366  * Flushes buffers of the file and causes all unwritten data to
2367  * be written.
2368  *
2369  * Return value: %TRUE on success, %FALSE otherwise.
2370  */
2371 gboolean FlushFileBuffers(gpointer handle)
2372 {
2373         WapiHandleType type;
2374
2375         type = _wapi_handle_type (handle);
2376         
2377         if(io_ops[type].flushfile==NULL) {
2378                 SetLastError (ERROR_INVALID_HANDLE);
2379                 return(FALSE);
2380         }
2381         
2382         return(io_ops[type].flushfile (handle));
2383 }
2384
2385 /**
2386  * SetEndOfFile:
2387  * @handle: The file handle to set.  The handle must have
2388  * %GENERIC_WRITE access.
2389  *
2390  * Moves the end-of-file position to the current position of the file
2391  * pointer.  This function is used to truncate or extend a file.
2392  *
2393  * Return value: %TRUE on success, %FALSE otherwise.
2394  */
2395 gboolean SetEndOfFile(gpointer handle)
2396 {
2397         WapiHandleType type;
2398
2399         type = _wapi_handle_type (handle);
2400         
2401         if (io_ops[type].setendoffile == NULL) {
2402                 SetLastError (ERROR_INVALID_HANDLE);
2403                 return(FALSE);
2404         }
2405         
2406         return(io_ops[type].setendoffile (handle));
2407 }
2408
2409 /**
2410  * SetFilePointer:
2411  * @handle: The file handle to set.  The handle must have
2412  * %GENERIC_READ or %GENERIC_WRITE access.
2413  * @movedistance: Low 32 bits of a signed value that specifies the
2414  * number of bytes to move the file pointer.
2415  * @highmovedistance: Pointer to the high 32 bits of a signed value
2416  * that specifies the number of bytes to move the file pointer, or
2417  * %NULL.
2418  * @method: The starting point for the file pointer move.
2419  *
2420  * Sets the file pointer of an open file.
2421  *
2422  * The distance to move the file pointer is calculated from
2423  * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2424  * @movedistance is the 32-bit signed value; otherwise, @movedistance
2425  * is the low 32 bits and @highmovedistance a pointer to the high 32
2426  * bits of a 64 bit signed value.  A positive distance moves the file
2427  * pointer forward from the position specified by @method; a negative
2428  * distance moves the file pointer backward.
2429  *
2430  * If the library is compiled without large file support,
2431  * @highmovedistance is ignored and its value is set to zero on a
2432  * successful return.
2433  *
2434  * Return value: On success, the low 32 bits of the new file pointer.
2435  * If @highmovedistance is not %NULL, the high 32 bits of the new file
2436  * pointer are stored there.  On failure, %INVALID_SET_FILE_POINTER.
2437  */
2438 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2439                        gint32 *highmovedistance, WapiSeekMethod method)
2440 {
2441         WapiHandleType type;
2442
2443         type = _wapi_handle_type (handle);
2444         
2445         if (io_ops[type].seek == NULL) {
2446                 SetLastError (ERROR_INVALID_HANDLE);
2447                 return(INVALID_SET_FILE_POINTER);
2448         }
2449         
2450         return(io_ops[type].seek (handle, movedistance, highmovedistance,
2451                                   method));
2452 }
2453
2454 /**
2455  * GetFileType:
2456  * @handle: The file handle to test.
2457  *
2458  * Finds the type of file @handle.
2459  *
2460  * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2461  * unknown.  %FILE_TYPE_DISK - @handle is a disk file.
2462  * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2463  * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2464  */
2465 WapiFileType GetFileType(gpointer handle)
2466 {
2467         WapiHandleType type;
2468
2469         if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2470                 SetLastError (ERROR_INVALID_HANDLE);
2471                 return(FILE_TYPE_UNKNOWN);
2472         }
2473
2474         type = _wapi_handle_type (handle);
2475         
2476         if (io_ops[type].getfiletype == NULL) {
2477                 SetLastError (ERROR_INVALID_HANDLE);
2478                 return(FILE_TYPE_UNKNOWN);
2479         }
2480         
2481         return(io_ops[type].getfiletype ());
2482 }
2483
2484 /**
2485  * GetFileSize:
2486  * @handle: The file handle to query.  The handle must have
2487  * %GENERIC_READ or %GENERIC_WRITE access.
2488  * @highsize: If non-%NULL, the high 32 bits of the file size are
2489  * stored here.
2490  *
2491  * Retrieves the size of the file @handle.
2492  *
2493  * If the library is compiled without large file support, @highsize
2494  * has its value set to zero on a successful return.
2495  *
2496  * Return value: On success, the low 32 bits of the file size.  If
2497  * @highsize is non-%NULL then the high 32 bits of the file size are
2498  * stored here.  On failure %INVALID_FILE_SIZE is returned.
2499  */
2500 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2501 {
2502         WapiHandleType type;
2503
2504         type = _wapi_handle_type (handle);
2505         
2506         if (io_ops[type].getfilesize == NULL) {
2507                 SetLastError (ERROR_INVALID_HANDLE);
2508                 return(INVALID_FILE_SIZE);
2509         }
2510         
2511         return(io_ops[type].getfilesize (handle, highsize));
2512 }
2513
2514 /**
2515  * GetFileTime:
2516  * @handle: The file handle to query.  The handle must have
2517  * %GENERIC_READ access.
2518  * @create_time: Points to a %WapiFileTime structure to receive the
2519  * number of ticks since the epoch that file was created.  May be
2520  * %NULL.
2521  * @last_access: Points to a %WapiFileTime structure to receive the
2522  * number of ticks since the epoch when file was last accessed.  May be
2523  * %NULL.
2524  * @last_write: Points to a %WapiFileTime structure to receive the
2525  * number of ticks since the epoch when file was last written to.  May
2526  * be %NULL.
2527  *
2528  * Finds the number of ticks since the epoch that the file referenced
2529  * by @handle was created, last accessed and last modified.  A tick is
2530  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2531  * GMT.
2532  *
2533  * Create time isn't recorded on POSIX file systems or reported by
2534  * stat(2), so that time is guessed by returning the oldest of the
2535  * other times.
2536  *
2537  * Return value: %TRUE on success, %FALSE otherwise.
2538  */
2539 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2540                      WapiFileTime *last_access, WapiFileTime *last_write)
2541 {
2542         WapiHandleType type;
2543
2544         type = _wapi_handle_type (handle);
2545         
2546         if (io_ops[type].getfiletime == NULL) {
2547                 SetLastError (ERROR_INVALID_HANDLE);
2548                 return(FALSE);
2549         }
2550         
2551         return(io_ops[type].getfiletime (handle, create_time, last_access,
2552                                          last_write));
2553 }
2554
2555 /**
2556  * SetFileTime:
2557  * @handle: The file handle to set.  The handle must have
2558  * %GENERIC_WRITE access.
2559  * @create_time: Points to a %WapiFileTime structure that contains the
2560  * number of ticks since the epoch that the file was created.  May be
2561  * %NULL.
2562  * @last_access: Points to a %WapiFileTime structure that contains the
2563  * number of ticks since the epoch when the file was last accessed.
2564  * May be %NULL.
2565  * @last_write: Points to a %WapiFileTime structure that contains the
2566  * number of ticks since the epoch when the file was last written to.
2567  * May be %NULL.
2568  *
2569  * Sets the number of ticks since the epoch that the file referenced
2570  * by @handle was created, last accessed or last modified.  A tick is
2571  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2572  * GMT.
2573  *
2574  * Create time isn't recorded on POSIX file systems, and is ignored.
2575  *
2576  * Return value: %TRUE on success, %FALSE otherwise.
2577  */
2578 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2579                      const WapiFileTime *last_access,
2580                      const WapiFileTime *last_write)
2581 {
2582         WapiHandleType type;
2583
2584         type = _wapi_handle_type (handle);
2585         
2586         if (io_ops[type].setfiletime == NULL) {
2587                 SetLastError (ERROR_INVALID_HANDLE);
2588                 return(FALSE);
2589         }
2590         
2591         return(io_ops[type].setfiletime (handle, create_time, last_access,
2592                                          last_write));
2593 }
2594
2595 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
2596  * January 1 1601 GMT
2597  */
2598
2599 #define TICKS_PER_MILLISECOND 10000L
2600 #define TICKS_PER_SECOND 10000000L
2601 #define TICKS_PER_MINUTE 600000000L
2602 #define TICKS_PER_HOUR 36000000000LL
2603 #define TICKS_PER_DAY 864000000000LL
2604
2605 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2606
2607 static const guint16 mon_yday[2][13]={
2608         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2609         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2610 };
2611
2612 /**
2613  * FileTimeToSystemTime:
2614  * @file_time: Points to a %WapiFileTime structure that contains the
2615  * number of ticks to convert.
2616  * @system_time: Points to a %WapiSystemTime structure to receive the
2617  * broken-out time.
2618  *
2619  * Converts a tick count into broken-out time values.
2620  *
2621  * Return value: %TRUE on success, %FALSE otherwise.
2622  */
2623 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2624                               WapiSystemTime *system_time)
2625 {
2626         gint64 file_ticks, totaldays, rem, y;
2627         const guint16 *ip;
2628         
2629         if(system_time==NULL) {
2630 #ifdef DEBUG
2631                 g_message("%s: system_time NULL", __func__);
2632 #endif
2633
2634                 SetLastError (ERROR_INVALID_PARAMETER);
2635                 return(FALSE);
2636         }
2637         
2638         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2639                 file_time->dwLowDateTime;
2640         
2641         /* Really compares if file_ticks>=0x8000000000000000
2642          * (LLONG_MAX+1) but we're working with a signed value for the
2643          * year and day calculation to work later
2644          */
2645         if(file_ticks<0) {
2646 #ifdef DEBUG
2647                 g_message("%s: file_time too big", __func__);
2648 #endif
2649
2650                 SetLastError (ERROR_INVALID_PARAMETER);
2651                 return(FALSE);
2652         }
2653
2654         totaldays=(file_ticks / TICKS_PER_DAY);
2655         rem = file_ticks % TICKS_PER_DAY;
2656 #ifdef DEBUG
2657         g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2658 #endif
2659
2660         system_time->wHour=rem/TICKS_PER_HOUR;
2661         rem %= TICKS_PER_HOUR;
2662 #ifdef DEBUG
2663         g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2664 #endif
2665         
2666         system_time->wMinute = rem / TICKS_PER_MINUTE;
2667         rem %= TICKS_PER_MINUTE;
2668 #ifdef DEBUG
2669         g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2670                   rem);
2671 #endif
2672         
2673         system_time->wSecond = rem / TICKS_PER_SECOND;
2674         rem %= TICKS_PER_SECOND;
2675 #ifdef DEBUG
2676         g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2677                   rem);
2678 #endif
2679         
2680         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2681 #ifdef DEBUG
2682         g_message("%s: Milliseconds: %d", __func__,
2683                   system_time->wMilliseconds);
2684 #endif
2685
2686         /* January 1, 1601 was a Monday, according to Emacs calendar */
2687         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2688 #ifdef DEBUG
2689         g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2690 #endif
2691         
2692         /* This algorithm to find year and month given days from epoch
2693          * from glibc
2694          */
2695         y=1601;
2696         
2697 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2698 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2699
2700         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2701                 /* Guess a corrected year, assuming 365 days per year */
2702                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2703 #ifdef DEBUG
2704                 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2705                           totaldays, yg,
2706                           y);
2707                 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2708                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2709 #endif
2710                 
2711                 /* Adjust days and y to match the guessed year. */
2712                 totaldays -= ((yg - y) * 365
2713                               + LEAPS_THRU_END_OF (yg - 1)
2714                               - LEAPS_THRU_END_OF (y - 1));
2715 #ifdef DEBUG
2716                 g_message("%s: totaldays: %lld", __func__, totaldays);
2717 #endif
2718                 y = yg;
2719 #ifdef DEBUG
2720                 g_message("%s: y: %lld", __func__, y);
2721 #endif
2722         }
2723         
2724         system_time->wYear = y;
2725 #ifdef DEBUG
2726         g_message("%s: Year: %d", __func__, system_time->wYear);
2727 #endif
2728
2729         ip = mon_yday[isleap(y)];
2730         
2731         for(y=11; totaldays < ip[y]; --y) {
2732                 continue;
2733         }
2734         totaldays-=ip[y];
2735 #ifdef DEBUG
2736         g_message("%s: totaldays: %lld", __func__, totaldays);
2737 #endif
2738         
2739         system_time->wMonth = y + 1;
2740 #ifdef DEBUG
2741         g_message("%s: Month: %d", __func__, system_time->wMonth);
2742 #endif
2743
2744         system_time->wDay = totaldays + 1;
2745 #ifdef DEBUG
2746         g_message("%s: Day: %d", __func__, system_time->wDay);
2747 #endif
2748         
2749         return(TRUE);
2750 }
2751
2752 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2753 {
2754         struct _WapiHandle_find find_handle = {0};
2755         gpointer handle;
2756         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2757         int result;
2758         
2759         if (pattern == NULL) {
2760 #ifdef DEBUG
2761                 g_message ("%s: pattern is NULL", __func__);
2762 #endif
2763
2764                 SetLastError (ERROR_PATH_NOT_FOUND);
2765                 return(INVALID_HANDLE_VALUE);
2766         }
2767
2768         utf8_pattern = mono_unicode_to_external (pattern);
2769         if (utf8_pattern == NULL) {
2770 #ifdef DEBUG
2771                 g_message ("%s: unicode conversion returned NULL", __func__);
2772 #endif
2773                 
2774                 SetLastError (ERROR_INVALID_NAME);
2775                 return(INVALID_HANDLE_VALUE);
2776         }
2777
2778 #ifdef DEBUG
2779         g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2780 #endif
2781         
2782         /* Figure out which bit of the pattern is the directory */
2783         dir_part = _wapi_dirname (utf8_pattern);
2784         entry_part = _wapi_basename (utf8_pattern);
2785
2786 #if 0
2787         /* Don't do this check for now, it breaks if directories
2788          * really do have metachars in their names (see bug 58116).
2789          * FIXME: Figure out a better solution to keep some checks...
2790          */
2791         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2792                 SetLastError (ERROR_INVALID_NAME);
2793                 g_free (dir_part);
2794                 g_free (entry_part);
2795                 g_free (utf8_pattern);
2796                 return(INVALID_HANDLE_VALUE);
2797         }
2798 #endif
2799
2800         /* The pattern can specify a directory or a set of files.
2801          *
2802          * The pattern can have wildcard characters ? and *, but only
2803          * in the section after the last directory delimiter.  (Return
2804          * ERROR_INVALID_NAME if there are wildcards in earlier path
2805          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
2806          * means "match one character", "??" seems to mean "match one
2807          * or two characters", "???" seems to mean "match one, two or
2808          * three characters", etc.  Windows will also try and match
2809          * the mangled "short name" of files, so 8 character patterns
2810          * with wildcards will show some surprising results.
2811          *
2812          * All the written documentation I can find says that '?' 
2813          * should only match one character, and doesn't mention '??',
2814          * '???' etc.  I'm going to assume that the strict behaviour
2815          * (ie '???' means three and only three characters) is the
2816          * correct one, because that lets me use fnmatch(3) rather
2817          * than mess around with regexes.
2818          */
2819
2820         find_handle.namelist = NULL;
2821         result = _wapi_io_scandir (dir_part, entry_part,
2822                                    &find_handle.namelist);
2823         
2824         if (result == 0) {
2825                 /* No files, which windows seems to call
2826                  * FILE_NOT_FOUND
2827                  */
2828                 SetLastError (ERROR_FILE_NOT_FOUND);
2829                 g_free (utf8_pattern);
2830                 g_free (entry_part);
2831                 g_free (dir_part);
2832                 return (INVALID_HANDLE_VALUE);
2833         }
2834         
2835         if (result < 0) {
2836 #ifdef DEBUG
2837                 gint errnum = errno;
2838 #endif
2839                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2840 #ifdef DEBUG
2841                 g_message ("%s: scandir error: %s", __func__,
2842                            g_strerror (errnum));
2843 #endif
2844                 g_free (utf8_pattern);
2845                 g_free (entry_part);
2846                 g_free (dir_part);
2847                 return (INVALID_HANDLE_VALUE);
2848         }
2849
2850         g_free (utf8_pattern);
2851         g_free (entry_part);
2852         
2853 #ifdef DEBUG
2854         g_message ("%s: Got %d matches", __func__, result);
2855 #endif
2856
2857         find_handle.dir_part = dir_part;
2858         find_handle.num = result;
2859         find_handle.count = 0;
2860         
2861         handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2862         if (handle == _WAPI_HANDLE_INVALID) {
2863                 g_warning ("%s: error creating find handle", __func__);
2864                 g_free (dir_part);
2865                 g_free (entry_part);
2866                 g_free (utf8_pattern);
2867                 SetLastError (ERROR_GEN_FAILURE);
2868                 
2869                 return(INVALID_HANDLE_VALUE);
2870         }
2871
2872         if (handle != INVALID_HANDLE_VALUE &&
2873             !FindNextFile (handle, find_data)) {
2874                 FindClose (handle);
2875                 SetLastError (ERROR_NO_MORE_FILES);
2876                 handle = INVALID_HANDLE_VALUE;
2877         }
2878
2879         return (handle);
2880 }
2881
2882 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2883 {
2884         struct _WapiHandle_find *find_handle;
2885         gboolean ok;
2886         struct stat buf, linkbuf;
2887         int result;
2888         gchar *filename;
2889         gchar *utf8_filename, *utf8_basename;
2890         gunichar2 *utf16_basename;
2891         time_t create_time;
2892         glong bytes;
2893         int thr_ret;
2894         gboolean ret = FALSE;
2895         
2896         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2897                                 (gpointer *)&find_handle);
2898         if(ok==FALSE) {
2899                 g_warning ("%s: error looking up find handle %p", __func__,
2900                            handle);
2901                 SetLastError (ERROR_INVALID_HANDLE);
2902                 return(FALSE);
2903         }
2904
2905         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2906                               handle);
2907         thr_ret = _wapi_handle_lock_handle (handle);
2908         g_assert (thr_ret == 0);
2909         
2910 retry:
2911         if (find_handle->count >= find_handle->num) {
2912                 SetLastError (ERROR_NO_MORE_FILES);
2913                 goto cleanup;
2914         }
2915
2916         /* stat next match */
2917
2918         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2919
2920         result = _wapi_stat (filename, &buf);
2921         if (result == -1 && errno == ENOENT) {
2922                 /* Might be a dangling symlink */
2923                 result = _wapi_lstat (filename, &buf);
2924         }
2925         
2926         if (result != 0) {
2927 #ifdef DEBUG
2928                 g_message ("%s: stat failed: %s", __func__, filename);
2929 #endif
2930
2931                 g_free (filename);
2932                 goto retry;
2933         }
2934
2935         result = _wapi_lstat (filename, &linkbuf);
2936         if (result != 0) {
2937 #ifdef DEBUG
2938                 g_message ("%s: lstat failed: %s", __func__, filename);
2939 #endif
2940
2941                 g_free (filename);
2942                 goto retry;
2943         }
2944
2945         utf8_filename = mono_utf8_from_external (filename);
2946         if (utf8_filename == NULL) {
2947                 /* We couldn't turn this filename into utf8 (eg the
2948                  * encoding of the name wasn't convertible), so just
2949                  * ignore it.
2950                  */
2951                 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2952                 
2953                 g_free (filename);
2954                 goto retry;
2955         }
2956         g_free (filename);
2957         
2958 #ifdef DEBUG
2959         g_message ("%s: Found [%s]", __func__, utf8_filename);
2960 #endif
2961         
2962         /* fill data block */
2963
2964         if (buf.st_mtime < buf.st_ctime)
2965                 create_time = buf.st_mtime;
2966         else
2967                 create_time = buf.st_ctime;
2968         
2969         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2970
2971         _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2972         _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2973         _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2974
2975         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2976                 find_data->nFileSizeHigh = 0;
2977                 find_data->nFileSizeLow = 0;
2978         } else {
2979                 find_data->nFileSizeHigh = buf.st_size >> 32;
2980                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2981         }
2982
2983         find_data->dwReserved0 = 0;
2984         find_data->dwReserved1 = 0;
2985
2986         utf8_basename = _wapi_basename (utf8_filename);
2987         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2988                                           NULL);
2989         if(utf16_basename==NULL) {
2990                 g_free (utf8_basename);
2991                 g_free (utf8_filename);
2992                 goto retry;
2993         }
2994         ret = TRUE;
2995         
2996         /* utf16 is 2 * utf8 */
2997         bytes *= 2;
2998
2999         memset (find_data->cFileName, '\0', (MAX_PATH*2));
3000
3001         /* Truncating a utf16 string like this might leave the last
3002          * char incomplete
3003          */
3004         memcpy (find_data->cFileName, utf16_basename,
3005                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3006
3007         find_data->cAlternateFileName [0] = 0;  /* not used */
3008
3009         g_free (utf8_basename);
3010         g_free (utf8_filename);
3011         g_free (utf16_basename);
3012
3013 cleanup:
3014         thr_ret = _wapi_handle_unlock_handle (handle);
3015         g_assert (thr_ret == 0);
3016         pthread_cleanup_pop (0);
3017         
3018         return(ret);
3019 }
3020
3021 /**
3022  * FindClose:
3023  * @wapi_handle: the find handle to close.
3024  *
3025  * Closes find handle @wapi_handle
3026  *
3027  * Return value: %TRUE on success, %FALSE otherwise.
3028  */
3029 gboolean FindClose (gpointer handle)
3030 {
3031         struct _WapiHandle_find *find_handle;
3032         gboolean ok;
3033         int thr_ret;
3034
3035         if (handle == NULL) {
3036                 SetLastError (ERROR_INVALID_HANDLE);
3037                 return(FALSE);
3038         }
3039         
3040         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3041                                 (gpointer *)&find_handle);
3042         if(ok==FALSE) {
3043                 g_warning ("%s: error looking up find handle %p", __func__,
3044                            handle);
3045                 SetLastError (ERROR_INVALID_HANDLE);
3046                 return(FALSE);
3047         }
3048
3049         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3050                               handle);
3051         thr_ret = _wapi_handle_lock_handle (handle);
3052         g_assert (thr_ret == 0);
3053         
3054         g_strfreev (find_handle->namelist);
3055         g_free (find_handle->dir_part);
3056
3057         thr_ret = _wapi_handle_unlock_handle (handle);
3058         g_assert (thr_ret == 0);
3059         pthread_cleanup_pop (0);
3060         
3061         _wapi_handle_unref (handle);
3062         
3063         return(TRUE);
3064 }
3065
3066 /**
3067  * CreateDirectory:
3068  * @name: a pointer to a NULL-terminated unicode string, that names
3069  * the directory to be created.
3070  * @security: ignored for now
3071  *
3072  * Creates directory @name
3073  *
3074  * Return value: %TRUE on success, %FALSE otherwise.
3075  */
3076 gboolean CreateDirectory (const gunichar2 *name,
3077                           WapiSecurityAttributes *security)
3078 {
3079         gchar *utf8_name;
3080         int result;
3081         
3082         if (name == NULL) {
3083 #ifdef DEBUG
3084                 g_message("%s: name is NULL", __func__);
3085 #endif
3086
3087                 SetLastError (ERROR_INVALID_NAME);
3088                 return(FALSE);
3089         }
3090         
3091         utf8_name = mono_unicode_to_external (name);
3092         if (utf8_name == NULL) {
3093 #ifdef DEBUG
3094                 g_message ("%s: unicode conversion returned NULL", __func__);
3095 #endif
3096         
3097                 SetLastError (ERROR_INVALID_NAME);
3098                 return FALSE;
3099         }
3100
3101         result = _wapi_mkdir (utf8_name, 0777);
3102
3103         if (result == 0) {
3104                 g_free (utf8_name);
3105                 return TRUE;
3106         }
3107
3108         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3109         g_free (utf8_name);
3110         return FALSE;
3111 }
3112
3113 /**
3114  * RemoveDirectory:
3115  * @name: a pointer to a NULL-terminated unicode string, that names
3116  * the directory to be removed.
3117  *
3118  * Removes directory @name
3119  *
3120  * Return value: %TRUE on success, %FALSE otherwise.
3121  */
3122 gboolean RemoveDirectory (const gunichar2 *name)
3123 {
3124         gchar *utf8_name;
3125         int result;
3126         
3127         if (name == NULL) {
3128 #ifdef DEBUG
3129                 g_message("%s: name is NULL", __func__);
3130 #endif
3131
3132                 SetLastError (ERROR_INVALID_NAME);
3133                 return(FALSE);
3134         }
3135
3136         utf8_name = mono_unicode_to_external (name);
3137         if (utf8_name == NULL) {
3138 #ifdef DEBUG
3139                 g_message ("%s: unicode conversion returned NULL", __func__);
3140 #endif
3141                 
3142                 SetLastError (ERROR_INVALID_NAME);
3143                 return FALSE;
3144         }
3145
3146         result = _wapi_rmdir (utf8_name);
3147         if (result == -1) {
3148                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3149                 g_free (utf8_name);
3150                 
3151                 return(FALSE);
3152         }
3153         g_free (utf8_name);
3154
3155         return(TRUE);
3156 }
3157
3158 /**
3159  * GetFileAttributes:
3160  * @name: a pointer to a NULL-terminated unicode filename.
3161  *
3162  * Gets the attributes for @name;
3163  *
3164  * Return value: %INVALID_FILE_ATTRIBUTES on failure
3165  */
3166 guint32 GetFileAttributes (const gunichar2 *name)
3167 {
3168         gchar *utf8_name;
3169         struct stat buf, linkbuf;
3170         int result;
3171         guint32 ret;
3172         
3173         if (name == NULL) {
3174 #ifdef DEBUG
3175                 g_message("%s: name is NULL", __func__);
3176 #endif
3177
3178                 SetLastError (ERROR_INVALID_NAME);
3179                 return(FALSE);
3180         }
3181         
3182         utf8_name = mono_unicode_to_external (name);
3183         if (utf8_name == NULL) {
3184 #ifdef DEBUG
3185                 g_message ("%s: unicode conversion returned NULL", __func__);
3186 #endif
3187
3188                 SetLastError (ERROR_INVALID_PARAMETER);
3189                 return (INVALID_FILE_ATTRIBUTES);
3190         }
3191
3192         result = _wapi_stat (utf8_name, &buf);
3193         if (result == -1 && errno == ENOENT) {
3194                 /* Might be a dangling symlink... */
3195                 result = _wapi_lstat (utf8_name, &buf);
3196         }
3197
3198         if (result != 0) {
3199                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3200                 g_free (utf8_name);
3201                 return (INVALID_FILE_ATTRIBUTES);
3202         }
3203
3204         result = _wapi_lstat (utf8_name, &linkbuf);
3205         if (result != 0) {
3206                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3207                 g_free (utf8_name);
3208                 return (INVALID_FILE_ATTRIBUTES);
3209         }
3210         
3211         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3212         
3213         g_free (utf8_name);
3214
3215         return(ret);
3216 }
3217
3218 /**
3219  * GetFileAttributesEx:
3220  * @name: a pointer to a NULL-terminated unicode filename.
3221  * @level: must be GetFileExInfoStandard
3222  * @info: pointer to a WapiFileAttributesData structure
3223  *
3224  * Gets attributes, size and filetimes for @name;
3225  *
3226  * Return value: %TRUE on success, %FALSE on failure
3227  */
3228 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3229 {
3230         gchar *utf8_name;
3231         WapiFileAttributesData *data;
3232
3233         struct stat buf, linkbuf;
3234         time_t create_time;
3235         int result;
3236         
3237         if (level != GetFileExInfoStandard) {
3238 #ifdef DEBUG
3239                 g_message ("%s: info level %d not supported.", __func__,
3240                            level);
3241 #endif
3242
3243                 SetLastError (ERROR_INVALID_PARAMETER);
3244                 return FALSE;
3245         }
3246         
3247         if (name == NULL) {
3248 #ifdef DEBUG
3249                 g_message("%s: name is NULL", __func__);
3250 #endif
3251
3252                 SetLastError (ERROR_INVALID_NAME);
3253                 return(FALSE);
3254         }
3255
3256         utf8_name = mono_unicode_to_external (name);
3257         if (utf8_name == NULL) {
3258 #ifdef DEBUG
3259                 g_message ("%s: unicode conversion returned NULL", __func__);
3260 #endif
3261
3262                 SetLastError (ERROR_INVALID_PARAMETER);
3263                 return FALSE;
3264         }
3265
3266         result = _wapi_stat (utf8_name, &buf);
3267         if (result == -1 && errno == ENOENT) {
3268                 /* Might be a dangling symlink... */
3269                 result = _wapi_lstat (utf8_name, &buf);
3270         }
3271         
3272         if (result != 0) {
3273                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3274                 g_free (utf8_name);
3275                 return FALSE;
3276         }
3277
3278         result = _wapi_lstat (utf8_name, &linkbuf);
3279         if (result != 0) {
3280                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3281                 g_free (utf8_name);
3282                 return(FALSE);
3283         }
3284
3285         /* fill data block */
3286
3287         data = (WapiFileAttributesData *)info;
3288
3289         if (buf.st_mtime < buf.st_ctime)
3290                 create_time = buf.st_mtime;
3291         else
3292                 create_time = buf.st_ctime;
3293         
3294         data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3295                                                                 &buf,
3296                                                                 &linkbuf);
3297
3298         g_free (utf8_name);
3299
3300         _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3301         _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3302         _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3303
3304         if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3305                 data->nFileSizeHigh = 0;
3306                 data->nFileSizeLow = 0;
3307         }
3308         else {
3309                 data->nFileSizeHigh = buf.st_size >> 32;
3310                 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3311         }
3312
3313         return TRUE;
3314 }
3315
3316 /**
3317  * SetFileAttributes
3318  * @name: name of file
3319  * @attrs: attributes to set
3320  *
3321  * Changes the attributes on a named file.
3322  *
3323  * Return value: %TRUE on success, %FALSE on failure.
3324  */
3325 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3326 {
3327         /* FIXME: think of something clever to do on unix */
3328         gchar *utf8_name;
3329         struct stat buf;
3330         int result;
3331
3332         /*
3333          * Currently we only handle one *internal* case, with a value that is
3334          * not standard: 0x80000000, which means `set executable bit'
3335          */
3336         
3337         if (name == NULL) {
3338 #ifdef DEBUG
3339                 g_message("%s: name is NULL", __func__);
3340 #endif
3341
3342                 SetLastError (ERROR_INVALID_NAME);
3343                 return(FALSE);
3344         }
3345
3346         utf8_name = mono_unicode_to_external (name);
3347         if (utf8_name == NULL) {
3348 #ifdef DEBUG
3349                 g_message ("%s: unicode conversion returned NULL", __func__);
3350 #endif
3351
3352                 SetLastError (ERROR_INVALID_NAME);
3353                 return FALSE;
3354         }
3355
3356         result = _wapi_stat (utf8_name, &buf);
3357         if (result != 0) {
3358                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3359                 g_free (utf8_name);
3360                 return FALSE;
3361         }
3362
3363         /* Contrary to the documentation, ms allows NORMAL to be
3364          * specified along with other attributes, so dont bother to
3365          * catch that case here.
3366          */
3367         if (attrs & FILE_ATTRIBUTE_READONLY) {
3368                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3369         } else {
3370                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3371         }
3372
3373         /* Ignore the other attributes for now */
3374
3375         if (attrs & 0x80000000){
3376                 mode_t exec_mask = 0;
3377
3378                 if ((buf.st_mode & S_IRUSR) != 0)
3379                         exec_mask |= S_IXUSR;
3380
3381                 if ((buf.st_mode & S_IRGRP) != 0)
3382                         exec_mask |= S_IXGRP;
3383
3384                 if ((buf.st_mode & S_IROTH) != 0)
3385                         exec_mask |= S_IXOTH;
3386
3387                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3388         }
3389         /* Don't bother to reset executable (might need to change this
3390          * policy)
3391          */
3392         
3393         g_free (utf8_name);
3394
3395         return(TRUE);
3396 }
3397
3398 /**
3399  * GetCurrentDirectory
3400  * @length: size of the buffer
3401  * @buffer: pointer to buffer that recieves path
3402  *
3403  * Retrieves the current directory for the current process.
3404  *
3405  * Return value: number of characters in buffer on success, zero on failure
3406  */
3407 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3408 {
3409         gunichar2 *utf16_path;
3410         glong count;
3411         gsize bytes;
3412
3413         if (getcwd ((char*)buffer, length) == NULL) {
3414                 if (errno == ERANGE) { /*buffer length is not big enough */ 
3415                         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*/
3416                         if (path == NULL)
3417                                 return 0;
3418                         utf16_path = mono_unicode_from_external (path, &bytes);
3419                         g_free (utf16_path);
3420                         g_free (path);
3421                         return (bytes/2)+1;
3422                 }
3423                 _wapi_set_last_error_from_errno ();
3424                 return 0;
3425         }
3426
3427         utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3428         count = (bytes/2)+1;
3429         g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3430
3431         /* Add the terminator */
3432         memset (buffer, '\0', bytes+2);
3433         memcpy (buffer, utf16_path, bytes);
3434         
3435         g_free (utf16_path);
3436
3437         return count;
3438 }
3439
3440 /**
3441  * SetCurrentDirectory
3442  * @path: path to new directory
3443  *
3444  * Changes the directory path for the current process.
3445  *
3446  * Return value: %TRUE on success, %FALSE on failure.
3447  */
3448 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3449 {
3450         gchar *utf8_path;
3451         gboolean result;
3452
3453         if (path == NULL) {
3454                 SetLastError (ERROR_INVALID_PARAMETER);
3455                 return(FALSE);
3456         }
3457         
3458         utf8_path = mono_unicode_to_external (path);
3459         if (_wapi_chdir (utf8_path) != 0) {
3460                 _wapi_set_last_error_from_errno ();
3461                 result = FALSE;
3462         }
3463         else
3464                 result = TRUE;
3465
3466         g_free (utf8_path);
3467         return result;
3468 }
3469
3470 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3471                      WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3472 {
3473         struct _WapiHandle_file pipe_read_handle = {0};
3474         struct _WapiHandle_file pipe_write_handle = {0};
3475         gpointer read_handle;
3476         gpointer write_handle;
3477         int filedes[2];
3478         int ret;
3479         
3480         mono_once (&io_ops_once, io_ops_init);
3481         
3482 #ifdef DEBUG
3483         g_message ("%s: Creating pipe", __func__);
3484 #endif
3485
3486         ret=pipe (filedes);
3487         if(ret==-1) {
3488 #ifdef DEBUG
3489                 g_message ("%s: Error creating pipe: %s", __func__,
3490                            strerror (errno));
3491 #endif
3492                 
3493                 _wapi_set_last_error_from_errno ();
3494                 return(FALSE);
3495         }
3496
3497         if (filedes[0] >= _wapi_fd_reserve ||
3498             filedes[1] >= _wapi_fd_reserve) {
3499 #ifdef DEBUG
3500                 g_message ("%s: File descriptor is too big", __func__);
3501 #endif
3502
3503                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3504                 
3505                 close (filedes[0]);
3506                 close (filedes[1]);
3507                 
3508                 return(FALSE);
3509         }
3510         
3511         /* filedes[0] is open for reading, filedes[1] for writing */
3512
3513         pipe_read_handle.fileaccess = GENERIC_READ;
3514         read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3515                                            &pipe_read_handle);
3516         if (read_handle == _WAPI_HANDLE_INVALID) {
3517                 g_warning ("%s: error creating pipe read handle", __func__);
3518                 close (filedes[0]);
3519                 close (filedes[1]);
3520                 SetLastError (ERROR_GEN_FAILURE);
3521                 
3522                 return(FALSE);
3523         }
3524         
3525         pipe_write_handle.fileaccess = GENERIC_WRITE;
3526         write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3527                                             &pipe_write_handle);
3528         if (write_handle == _WAPI_HANDLE_INVALID) {
3529                 g_warning ("%s: error creating pipe write handle", __func__);
3530                 _wapi_handle_unref (read_handle);
3531                 
3532                 close (filedes[0]);
3533                 close (filedes[1]);
3534                 SetLastError (ERROR_GEN_FAILURE);
3535                 
3536                 return(FALSE);
3537         }
3538         
3539         *readpipe = read_handle;
3540         *writepipe = write_handle;
3541
3542 #ifdef DEBUG
3543         g_message ("%s: Returning pipe: read handle %p, write handle %p",
3544                    __func__, read_handle, write_handle);
3545 #endif
3546
3547         return(TRUE);
3548 }
3549
3550 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3551 {
3552         gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3553         gunichar2 *tmpdir16=NULL;
3554         glong dirlen;
3555         gsize bytes;
3556         guint32 ret;
3557         
3558         if(tmpdir[strlen (tmpdir)]!='/') {
3559                 g_free (tmpdir);
3560                 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3561         }
3562         
3563         tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3564         if(tmpdir16==NULL) {
3565                 g_free (tmpdir);
3566                 return(0);
3567         } else {
3568                 dirlen=(bytes/2);
3569                 
3570                 if(dirlen+1>len) {
3571 #ifdef DEBUG
3572                         g_message ("%s: Size %d smaller than needed (%ld)",
3573                                    __func__, len, dirlen+1);
3574 #endif
3575                 
3576                         ret=dirlen+1;
3577                 } else {
3578                         /* Add the terminator */
3579                         memset (buf, '\0', bytes+2);
3580                         memcpy (buf, tmpdir16, bytes);
3581                 
3582                         ret=dirlen;
3583                 }
3584         }
3585
3586         if(tmpdir16!=NULL) {
3587                 g_free (tmpdir16);
3588         }
3589         g_free (tmpdir);
3590         
3591         return(ret);
3592 }
3593
3594 #ifdef HAVE_GETFSSTAT
3595 /* Darwin has getfsstat */
3596 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3597 {
3598         struct statfs *stats;
3599         int size, n, i;
3600         gunichar2 *dir;
3601         glong length, total = 0;
3602         
3603         n = getfsstat (NULL, 0, MNT_NOWAIT);
3604         if (n == -1)
3605                 return 0;
3606         size = n * sizeof (struct statfs);
3607         stats = (struct statfs *) g_malloc (size);
3608         if (stats == NULL)
3609                 return 0;
3610         if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3611                 g_free (stats);
3612                 return 0;
3613         }
3614         for (i = 0; i < n; i++){
3615                 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3616                 if (total + length < len){
3617                         memcpy (buf + total, dir, sizeof (gunichar2) * length);
3618                         buf [total+length] = 0;
3619                 } 
3620                 g_free (dir);
3621                 total += length + 1;
3622         }
3623         if (total < len)
3624                 buf [total] = 0;
3625         total++;
3626         g_free (stats);
3627         return total;
3628 }
3629 #else
3630 /* In-place octal sequence replacement */
3631 static void
3632 unescape_octal (gchar *str)
3633 {
3634         gchar *rptr;
3635         gchar *wptr;
3636
3637         if (str == NULL)
3638                 return;
3639
3640         rptr = wptr = str;
3641         while (*rptr != '\0') {
3642                 if (*rptr == '\\') {
3643                         char c;
3644                         rptr++;
3645                         c = (*(rptr++) - '0') << 6;
3646                         c += (*(rptr++) - '0') << 3;
3647                         c += *(rptr++) - '0';
3648                         *wptr++ = c;
3649                 } else if (wptr != rptr) {
3650                         *wptr++ = *rptr++;
3651                 } else {
3652                         rptr++; wptr++;
3653                 }
3654         }
3655         *wptr = '\0';
3656 }
3657 #if __linux__
3658 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3659 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3660 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3661
3662 typedef struct 
3663 {
3664         glong total;
3665         guint32 buffer_index;
3666         guint32 mountpoint_index;
3667         guint32 field_number;
3668         guint32 allocated_size;
3669         guint32 fsname_index;
3670         guint32 fstype_index;
3671         gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3672         gchar *mountpoint_allocated;
3673         gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3674         gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3675         gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3676         ssize_t nbytes;
3677         gchar delimiter;
3678         gboolean check_mount_source;
3679 } LinuxMountInfoParseState;
3680
3681 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3682 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3683 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3684 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3685 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3686
3687 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3688 {
3689         int fd;
3690         gint32 ret = 0;
3691         LinuxMountInfoParseState state;
3692         gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3693
3694         memset (buf, 0, len * sizeof (gunichar2));
3695         fd = open ("/proc/self/mountinfo", O_RDONLY);
3696         if (fd != -1)
3697                 parser = GetLogicalDriveStrings_MountInfo;
3698         else {
3699                 fd = open ("/proc/mounts", O_RDONLY);
3700                 if (fd != -1)
3701                         parser = GetLogicalDriveStrings_Mounts;
3702         }
3703
3704         if (!parser) {
3705                 ret = GetLogicalDriveStrings_Mtab (len, buf);
3706                 goto done_and_out;
3707         }
3708
3709         memset (&state, 0, sizeof (LinuxMountInfoParseState));
3710         state.field_number = 1;
3711         state.delimiter = ' ';
3712
3713         while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3714                 state.buffer_index = 0;
3715
3716                 while ((*parser)(len, buf, &state)) {
3717                         if (state.buffer [state.buffer_index] == '\n') {
3718                                 gboolean quit = add_drive_string (len, buf, &state);
3719                                 state.field_number = 1;
3720                                 state.buffer_index++;
3721                                 if (state.mountpoint_allocated) {
3722                                         g_free (state.mountpoint_allocated);
3723                                         state.mountpoint_allocated = NULL;
3724                                 }
3725                                 if (quit) {
3726                                         ret = state.total;
3727                                         goto done_and_out;
3728                                 }
3729                         }
3730                 }
3731         };
3732         ret = state.total;
3733
3734   done_and_out:
3735         if (fd != -1)
3736                 close (fd);
3737         return ret;
3738 }
3739
3740 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3741 {
3742         gchar *ptr;
3743
3744         if (state->field_number == 1)
3745                 state->check_mount_source = TRUE;
3746
3747         while (state->buffer_index < (guint32)state->nbytes) {
3748                 if (state->buffer [state->buffer_index] == state->delimiter) {
3749                         state->field_number++;
3750                         switch (state->field_number) {
3751                                 case 2:
3752                                         state->mountpoint_index = 0;
3753                                         break;
3754
3755                                 case 3:
3756                                         if (state->mountpoint_allocated)
3757                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3758                                         else
3759                                                 state->mountpoint [state->mountpoint_index] = 0;
3760                                         break;
3761
3762                                 default:
3763                                         ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3764                                         if (ptr)
3765                                                 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3766                                         else
3767                                                 state->buffer_index = state->nbytes;
3768                                         return TRUE;
3769                         }
3770                         state->buffer_index++;
3771                         continue;
3772                 } else if (state->buffer [state->buffer_index] == '\n')
3773                         return TRUE;
3774
3775                 switch (state->field_number) {
3776                         case 1:
3777                                 if (state->check_mount_source) {
3778                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3779                                                 /* We can ignore the rest, it's a device
3780                                                  * path */
3781                                                 state->check_mount_source = FALSE;
3782                                                 state->fsname [state->fsname_index++] = '/';
3783                                                 break;
3784                                         }
3785                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3786                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3787                                 }
3788                                 break;
3789
3790                         case 2:
3791                                 append_to_mountpoint (state);
3792                                 break;
3793
3794                         case 3:
3795                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3796                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3797                                 break;
3798                 }
3799
3800                 state->buffer_index++;
3801         }
3802
3803         return FALSE;
3804 }
3805
3806 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3807 {
3808         while (state->buffer_index < (guint32)state->nbytes) {
3809                 if (state->buffer [state->buffer_index] == state->delimiter) {
3810                         state->field_number++;
3811                         switch (state->field_number) {
3812                                 case 5:
3813                                         state->mountpoint_index = 0;
3814                                         break;
3815
3816                                 case 6:
3817                                         if (state->mountpoint_allocated)
3818                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3819                                         else
3820                                                 state->mountpoint [state->mountpoint_index] = 0;
3821                                         break;
3822
3823                                 case 7:
3824                                         state->delimiter = '-';
3825                                         break;
3826
3827                                 case 8:
3828                                         state->delimiter = ' ';
3829                                         break;
3830
3831                                 case 10:
3832                                         state->check_mount_source = TRUE;
3833                                         break;
3834                         }
3835                         state->buffer_index++;
3836                         continue;
3837                 } else if (state->buffer [state->buffer_index] == '\n')
3838                         return TRUE;
3839
3840                 switch (state->field_number) {
3841                         case 5:
3842                                 append_to_mountpoint (state);
3843                                 break;
3844
3845                         case 9:
3846                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3847                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3848                                 break;
3849
3850                         case 10:
3851                                 if (state->check_mount_source) {
3852                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3853                                                 /* We can ignore the rest, it's a device
3854                                                  * path */
3855                                                 state->check_mount_source = FALSE;
3856                                                 state->fsname [state->fsname_index++] = '/';
3857                                                 break;
3858                                         }
3859                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3860                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3861                                 }
3862                                 break;
3863                 }
3864
3865                 state->buffer_index++;
3866         }
3867
3868         return FALSE;
3869 }
3870
3871 static void
3872 append_to_mountpoint (LinuxMountInfoParseState *state)
3873 {
3874         gchar ch = state->buffer [state->buffer_index];
3875         if (state->mountpoint_allocated) {
3876                 if (state->mountpoint_index >= state->allocated_size) {
3877                         guint32 newsize = (state->allocated_size << 1) + 1;
3878                         gchar *newbuf = g_malloc0 (newsize * sizeof (gchar));
3879
3880                         memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3881                         g_free (state->mountpoint_allocated);
3882                         state->mountpoint_allocated = newbuf;
3883                         state->allocated_size = newsize;
3884                 }
3885                 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3886         } else {
3887                 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3888                         state->allocated_size = (state->mountpoint_index << 1) + 1;
3889                         state->mountpoint_allocated = g_malloc0 (state->allocated_size * sizeof (gchar));
3890                         memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3891                         state->mountpoint_allocated [state->mountpoint_index++] = ch;
3892                 } else
3893                         state->mountpoint [state->mountpoint_index++] = ch;
3894         }
3895 }
3896
3897 static gboolean
3898 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3899 {
3900         gboolean quit = FALSE;
3901         gboolean ignore_entry;
3902
3903         if (state->fsname_index == 1 && state->fsname [0] == '/')
3904                 ignore_entry = FALSE;
3905         else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0)
3906                 ignore_entry = TRUE;
3907         else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3908                 /* Ignore GNOME's gvfs */
3909                 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3910                         ignore_entry = TRUE;
3911                 else
3912                         ignore_entry = FALSE;
3913         } else
3914                 ignore_entry = TRUE;
3915
3916         if (!ignore_entry) {
3917                 gunichar2 *dir;
3918                 glong length;
3919                 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3920
3921                 unescape_octal (mountpoint);
3922                 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3923                 if (state->total + length + 1 > len) {
3924                         quit = TRUE;
3925                         state->total = len * 2;
3926                 } else {
3927                         length++;
3928                         memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3929                         state->total += length;
3930                 }
3931                 g_free (dir);
3932         }
3933         state->fsname_index = 0;
3934         state->fstype_index = 0;
3935
3936         return quit;
3937 }
3938 #else
3939 gint32
3940 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3941 {
3942         return GetLogicalDriveStrings_Mtab (len, buf);
3943 }
3944 #endif
3945 static gint32
3946 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3947 {
3948         FILE *fp;
3949         gunichar2 *ptr, *dir;
3950         glong length, total = 0;
3951         gchar buffer [512];
3952         gchar **splitted;
3953
3954         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
3955         buf [0] = '/';
3956         buf [1] = 0;
3957         buf [2] = 0;
3958
3959         /* Sigh, mntent and friends don't work well.
3960          * It stops on the first line that doesn't begin with a '/'.
3961          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3962         fp = fopen ("/etc/mtab", "rt");
3963         if (fp == NULL) {
3964                 fp = fopen ("/etc/mnttab", "rt");
3965                 if (fp == NULL)
3966                         return 1;
3967         }
3968
3969         ptr = buf;
3970         while (fgets (buffer, 512, fp) != NULL) {
3971                 if (*buffer != '/')
3972                         continue;
3973
3974                 splitted = g_strsplit (buffer, " ", 0);
3975                 if (!*splitted || !*(splitted + 1)) {
3976                         g_strfreev (splitted);
3977                         continue;
3978                 }
3979
3980                 unescape_octal (*(splitted + 1));
3981                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3982                 g_strfreev (splitted);
3983                 if (total + length + 1 > len) {
3984                         fclose (fp);
3985                         g_free (dir);
3986                         return len * 2; /* guess */
3987                 }
3988
3989                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3990                 g_free (dir);
3991                 total += length + 1;
3992         }
3993
3994         fclose (fp);
3995         return total;
3996 /* Commented out, does not work with my mtab!!! - Gonz */
3997 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3998 {
3999         FILE *fp;
4000         struct mntent *mnt;
4001         gunichar2 *ptr, *dir;
4002         glong len, total = 0;
4003         
4004
4005         fp = setmntent ("/etc/mtab", "rt");
4006         if (fp == NULL) {
4007                 fp = setmntent ("/etc/mnttab", "rt");
4008                 if (fp == NULL)
4009                         return;
4010         }
4011
4012         ptr = buf;
4013         while ((mnt = getmntent (fp)) != NULL) {
4014                 g_print ("GOT %s\n", mnt->mnt_dir);
4015                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4016                 if (total + len + 1 > len) {
4017                         return len * 2; /* guess */
4018                 }
4019
4020                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4021                 g_free (dir);
4022                 total += len + 1;
4023         }
4024
4025         endmntent (fp);
4026         return total;
4027 }
4028 #endif
4029 }
4030 #endif
4031
4032 #if (defined(HAVE_STATVFS) || defined(HAVE_STATFS)) && !defined(PLATFORM_ANDROID)
4033 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4034                             WapiULargeInteger *total_number_of_bytes,
4035                             WapiULargeInteger *total_number_of_free_bytes)
4036 {
4037 #ifdef HAVE_STATVFS
4038         struct statvfs fsstat;
4039 #elif defined(HAVE_STATFS)
4040         struct statfs fsstat;
4041 #endif
4042         gboolean isreadonly;
4043         gchar *utf8_path_name;
4044         int ret;
4045         unsigned long block_size;
4046
4047         if (path_name == NULL) {
4048                 utf8_path_name = g_strdup (g_get_current_dir());
4049                 if (utf8_path_name == NULL) {
4050                         SetLastError (ERROR_DIRECTORY);
4051                         return(FALSE);
4052                 }
4053         }
4054         else {
4055                 utf8_path_name = mono_unicode_to_external (path_name);
4056                 if (utf8_path_name == NULL) {
4057 #ifdef DEBUG
4058                         g_message("%s: unicode conversion returned NULL", __func__);
4059 #endif
4060
4061                         SetLastError (ERROR_INVALID_NAME);
4062                         return(FALSE);
4063                 }
4064         }
4065
4066         do {
4067 #ifdef HAVE_STATVFS
4068                 ret = statvfs (utf8_path_name, &fsstat);
4069                 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4070                 block_size = fsstat.f_frsize;
4071 #elif defined(HAVE_STATFS)
4072                 ret = statfs (utf8_path_name, &fsstat);
4073                 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4074                 block_size = fsstat.f_bsize;
4075 #endif
4076         } while(ret == -1 && errno == EINTR);
4077
4078         g_free(utf8_path_name);
4079
4080         if (ret == -1) {
4081                 _wapi_set_last_error_from_errno ();
4082 #ifdef DEBUG
4083                 g_message ("%s: statvfs failed: %s", __func__, strerror (errno));
4084 #endif
4085                 return(FALSE);
4086         }
4087
4088         /* total number of free bytes for non-root */
4089         if (free_bytes_avail != NULL) {
4090                 if (isreadonly) {
4091                         free_bytes_avail->QuadPart = 0;
4092                 }
4093                 else {
4094                         free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
4095                 }
4096         }
4097
4098         /* total number of bytes available for non-root */
4099         if (total_number_of_bytes != NULL) {
4100                 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
4101         }
4102
4103         /* total number of bytes available for root */
4104         if (total_number_of_free_bytes != NULL) {
4105                 if (isreadonly) {
4106                         total_number_of_free_bytes->QuadPart = 0;
4107                 }
4108                 else {
4109                         total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
4110                 }
4111         }
4112         
4113         return(TRUE);
4114 }
4115 #else
4116 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
4117                             WapiULargeInteger *total_number_of_bytes,
4118                             WapiULargeInteger *total_number_of_free_bytes)
4119 {
4120         if (free_bytes_avail != NULL) {
4121                 free_bytes_avail->QuadPart = (guint64) -1;
4122         }
4123
4124         if (total_number_of_bytes != NULL) {
4125                 total_number_of_bytes->QuadPart = (guint64) -1;
4126         }
4127
4128         if (total_number_of_free_bytes != NULL) {
4129                 total_number_of_free_bytes->QuadPart = (guint64) -1;
4130         }
4131
4132         return(TRUE);
4133 }
4134 #endif
4135
4136 /*
4137  * General Unix support
4138  */
4139 typedef struct {
4140         guint32 drive_type;
4141 #if __linux__
4142         const long fstypeid;
4143 #endif
4144         const gchar* fstype;
4145 } _wapi_drive_type;
4146
4147 static _wapi_drive_type _wapi_drive_types[] = {
4148 #if PLATFORM_MACOSX
4149         { DRIVE_REMOTE, "afp" },
4150         { DRIVE_REMOTE, "autofs" },
4151         { DRIVE_CDROM, "cddafs" },
4152         { DRIVE_CDROM, "cd9660" },
4153         { DRIVE_RAMDISK, "devfs" },
4154         { DRIVE_FIXED, "exfat" },
4155         { DRIVE_RAMDISK, "fdesc" },
4156         { DRIVE_REMOTE, "ftp" },
4157         { DRIVE_FIXED, "hfs" },
4158         { DRIVE_FIXED, "msdos" },
4159         { DRIVE_REMOTE, "nfs" },
4160         { DRIVE_FIXED, "ntfs" },
4161         { DRIVE_REMOTE, "smbfs" },
4162         { DRIVE_FIXED, "udf" },
4163         { DRIVE_REMOTE, "webdav" },
4164         { DRIVE_UNKNOWN, NULL }
4165 #elif __linux__
4166         { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4167         { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4168         { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4169         { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4170         { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4171         { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4172         { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4173         { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4174         { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4175         { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4176         { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4177         { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4178         { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4179         { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4180         { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4181         { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4182         { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4183         { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4184         { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4185         { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4186         { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4187         { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4188         { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4189         { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4190         { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4191         { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4192         { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4193         { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4194         { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4195         { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4196         { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4197         { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4198         { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4199         { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4200         { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4201         { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4202         { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4203         { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4204         { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4205         { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4206         { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4207         { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4208         { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4209         { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4210         { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4211         { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4212         { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4213         { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4214         { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4215         { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4216         { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4217         { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4218         { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4219         { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4220         { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4221         { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4222         { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4223         { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4224         { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4225         { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4226         { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4227         { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4228         { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4229         { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4230         { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4231         { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4232         { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4233         { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4234         { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4235         { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4236         { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4237         { DRIVE_UNKNOWN, 0, NULL}
4238 #else
4239         { DRIVE_RAMDISK, "ramfs"      },
4240         { DRIVE_RAMDISK, "tmpfs"      },
4241         { DRIVE_RAMDISK, "proc"       },
4242         { DRIVE_RAMDISK, "sysfs"      },
4243         { DRIVE_RAMDISK, "debugfs"    },
4244         { DRIVE_RAMDISK, "devpts"     },
4245         { DRIVE_RAMDISK, "securityfs" },
4246         { DRIVE_CDROM,   "iso9660"    },
4247         { DRIVE_FIXED,   "ext2"       },
4248         { DRIVE_FIXED,   "ext3"       },
4249         { DRIVE_FIXED,   "ext4"       },
4250         { DRIVE_FIXED,   "sysv"       },
4251         { DRIVE_FIXED,   "reiserfs"   },
4252         { DRIVE_FIXED,   "ufs"        },
4253         { DRIVE_FIXED,   "vfat"       },
4254         { DRIVE_FIXED,   "msdos"      },
4255         { DRIVE_FIXED,   "udf"        },
4256         { DRIVE_FIXED,   "hfs"        },
4257         { DRIVE_FIXED,   "hpfs"       },
4258         { DRIVE_FIXED,   "qnx4"       },
4259         { DRIVE_FIXED,   "ntfs"       },
4260         { DRIVE_FIXED,   "ntfs-3g"    },
4261         { DRIVE_REMOTE,  "smbfs"      },
4262         { DRIVE_REMOTE,  "fuse"       },
4263         { DRIVE_REMOTE,  "nfs"        },
4264         { DRIVE_REMOTE,  "nfs4"       },
4265         { DRIVE_REMOTE,  "cifs"       },
4266         { DRIVE_REMOTE,  "ncpfs"      },
4267         { DRIVE_REMOTE,  "coda"       },
4268         { DRIVE_REMOTE,  "afs"        },
4269         { DRIVE_UNKNOWN, NULL         }
4270 #endif
4271 };
4272
4273 #if __linux__
4274 static guint32 _wapi_get_drive_type(long f_type)
4275 {
4276         _wapi_drive_type *current;
4277
4278         current = &_wapi_drive_types[0];
4279         while (current->drive_type != DRIVE_UNKNOWN) {
4280                 if (current->fstypeid == f_type)
4281                         return current->drive_type;
4282                 current++;
4283         }
4284
4285         return DRIVE_UNKNOWN;
4286 }
4287 #else
4288 static guint32 _wapi_get_drive_type(const gchar* fstype)
4289 {
4290         _wapi_drive_type *current;
4291
4292         current = &_wapi_drive_types[0];
4293         while (current->drive_type != DRIVE_UNKNOWN) {
4294                 if (strcmp (current->fstype, fstype) == 0)
4295                         break;
4296
4297                 current++;
4298         }
4299         
4300         return current->drive_type;
4301 }
4302 #endif
4303
4304 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4305 static guint32
4306 GetDriveTypeFromPath (const char *utf8_root_path_name)
4307 {
4308         struct statfs buf;
4309         
4310         if (statfs (utf8_root_path_name, &buf) == -1)
4311                 return DRIVE_UNKNOWN;
4312 #if PLATFORM_MACOSX
4313         return _wapi_get_drive_type (buf.f_fstypename);
4314 #else
4315         return _wapi_get_drive_type (buf.f_type);
4316 #endif
4317 }
4318 #else
4319 static guint32
4320 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4321 {
4322         guint32 drive_type;
4323         FILE *fp;
4324         gchar buffer [512];
4325         gchar **splitted;
4326
4327         fp = fopen ("/etc/mtab", "rt");
4328         if (fp == NULL) {
4329                 fp = fopen ("/etc/mnttab", "rt");
4330                 if (fp == NULL) 
4331                         return(DRIVE_UNKNOWN);
4332         }
4333
4334         drive_type = DRIVE_NO_ROOT_DIR;
4335         while (fgets (buffer, 512, fp) != NULL) {
4336                 splitted = g_strsplit (buffer, " ", 0);
4337                 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4338                         g_strfreev (splitted);
4339                         continue;
4340                 }
4341
4342                 /* compare given root_path_name with the one from mtab, 
4343                   if length of utf8_root_path_name is zero it must be the root dir */
4344                 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4345                     (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4346                         drive_type = _wapi_get_drive_type (*(splitted + 2));
4347                         g_strfreev (splitted);
4348                         break;
4349                 }
4350
4351                 g_strfreev (splitted);
4352         }
4353
4354         fclose (fp);
4355         return drive_type;
4356 }
4357 #endif
4358
4359 guint32 GetDriveType(const gunichar2 *root_path_name)
4360 {
4361         gchar *utf8_root_path_name;
4362         guint32 drive_type;
4363
4364         if (root_path_name == NULL) {
4365                 utf8_root_path_name = g_strdup (g_get_current_dir());
4366                 if (utf8_root_path_name == NULL) {
4367                         return(DRIVE_NO_ROOT_DIR);
4368                 }
4369         }
4370         else {
4371                 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4372                 if (utf8_root_path_name == NULL) {
4373 #ifdef DEBUG
4374                         g_message("%s: unicode conversion returned NULL", __func__);
4375 #endif
4376                         return(DRIVE_NO_ROOT_DIR);
4377                 }
4378                 
4379                 /* strip trailing slash for compare below */
4380                 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4381                         utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4382                 }
4383         }
4384         drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4385         g_free (utf8_root_path_name);
4386
4387         return (drive_type);
4388 }
4389
4390 static const gchar*
4391 get_fstypename (gchar *utfpath)
4392 {
4393 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4394         struct statfs stat;
4395 #if __linux__
4396         _wapi_drive_type *current;
4397 #endif
4398         if (statfs (utfpath, &stat) == -1)
4399                 return NULL;
4400 #if PLATFORM_MACOSX
4401         return stat.f_fstypename;
4402 #else
4403         current = &_wapi_drive_types[0];
4404         while (current->drive_type != DRIVE_UNKNOWN) {
4405                 if (stat.f_type == current->fstypeid)
4406                         return current->fstype;
4407                 current++;
4408         }
4409         return NULL;
4410 #endif
4411 #else
4412         return NULL;
4413 #endif
4414 }
4415
4416 /* Linux has struct statfs which has a different layout */
4417 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD)
4418 gboolean
4419 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4420 {
4421         gchar *utfpath;
4422         const gchar *fstypename;
4423         gboolean status = FALSE;
4424         glong len;
4425         
4426         // We only support getting the file system type
4427         if (fsbuffer == NULL)
4428                 return 0;
4429         
4430         utfpath = mono_unicode_to_external (path);
4431         if ((fstypename = get_fstypename (utfpath)) != NULL){
4432                 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4433                 if (ret != NULL && len < fsbuffersize){
4434                         memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4435                         fsbuffer [len] = 0;
4436                         status = TRUE;
4437                 }
4438                 if (ret != NULL)
4439                         g_free (ret);
4440         }
4441         g_free (utfpath);
4442         return status;
4443 }
4444 #endif