win32: define _WIN32_WINNT globally
[platform/upstream/glib.git] / gio / glocalfile.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #if HAVE_SYS_STATFS_H
35 #include <sys/statfs.h>
36 #endif
37 #if HAVE_SYS_STATVFS_H
38 #include <sys/statvfs.h>
39 #endif
40 #if HAVE_SYS_VFS_H
41 #include <sys/vfs.h>
42 #elif HAVE_SYS_MOUNT_H
43 #if HAVE_SYS_PARAM_H
44 #include <sys/param.h>
45 #endif
46 #include <sys/mount.h>
47 #endif
48
49 #ifndef O_BINARY
50 #define O_BINARY 0
51 #endif
52
53 #include "gfileattribute.h"
54 #include "glocalfile.h"
55 #include "glocalfileinfo.h"
56 #include "glocalfileenumerator.h"
57 #include "glocalfileinputstream.h"
58 #include "glocalfileoutputstream.h"
59 #include "glocalfileiostream.h"
60 #include "glocaldirectorymonitor.h"
61 #include "glocalfilemonitor.h"
62 #include "gmountprivate.h"
63 #include "gunixmounts.h"
64 #include "gioerror.h"
65 #include <glib/gstdio.h>
66 #include "glibintl.h"
67
68 #ifdef G_OS_WIN32
69 #include <windows.h>
70 #include <io.h>
71 #include <direct.h>
72
73 #ifndef FILE_READ_ONLY_VOLUME
74 #define FILE_READ_ONLY_VOLUME           0x00080000
75 #endif
76
77 #ifndef S_ISDIR
78 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
79 #endif
80 #ifndef S_ISLNK
81 #define S_ISLNK(m) (0)
82 #endif
83 #endif
84
85
86 static void g_local_file_file_iface_init (GFileIface *iface);
87
88 static GFileAttributeInfoList *local_writable_attributes = NULL;
89 static /* GFileAttributeInfoList * */ gsize local_writable_namespaces = 0;
90
91 struct _GLocalFile
92 {
93   GObject parent_instance;
94
95   char *filename;
96 };
97
98 #define g_local_file_get_type _g_local_file_get_type
99 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
100                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
101                                                 g_local_file_file_iface_init))
102
103 static char *find_mountpoint_for (const char *file, dev_t dev);
104
105 static void
106 g_local_file_finalize (GObject *object)
107 {
108   GLocalFile *local;
109
110   local = G_LOCAL_FILE (object);
111
112   g_free (local->filename);
113
114   G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
115 }
116
117 static void
118 g_local_file_class_init (GLocalFileClass *klass)
119 {
120   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
121   GFileAttributeInfoList *list;
122
123   gobject_class->finalize = g_local_file_finalize;
124
125   /* Set up attribute lists */
126
127   /* Writable attributes: */
128
129   list = g_file_attribute_info_list_new ();
130
131   g_file_attribute_info_list_add (list,
132                                   G_FILE_ATTRIBUTE_UNIX_MODE,
133                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
134                                   G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
135                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
136   
137 #ifdef HAVE_CHOWN
138   g_file_attribute_info_list_add (list,
139                                   G_FILE_ATTRIBUTE_UNIX_UID,
140                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
141                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
142   g_file_attribute_info_list_add (list,
143                                   G_FILE_ATTRIBUTE_UNIX_GID,
144                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
145                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
146 #endif
147   
148 #ifdef HAVE_SYMLINK
149   g_file_attribute_info_list_add (list,
150                                   G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
151                                   G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
152                                   0);
153 #endif
154   
155 #ifdef HAVE_UTIMES
156   g_file_attribute_info_list_add (list,
157                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
158                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
159                                   G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
160                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
161   g_file_attribute_info_list_add (list,
162                                   G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
163                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
164                                   G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
165                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
166   /* When copying, the target file is accessed. Replicating
167    * the source access time does not make sense in this case.
168    */
169   g_file_attribute_info_list_add (list,
170                                   G_FILE_ATTRIBUTE_TIME_ACCESS,
171                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
172                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
173   g_file_attribute_info_list_add (list,
174                                   G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
175                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
176                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
177 #endif
178
179   local_writable_attributes = list;
180 }
181
182 static void
183 g_local_file_init (GLocalFile *local)
184 {
185 }
186
187
188 static char *
189 canonicalize_filename (const char *filename)
190 {
191   char *canon, *start, *p, *q;
192   char *cwd;
193   int i;
194   
195   if (!g_path_is_absolute (filename))
196     {
197       cwd = g_get_current_dir ();
198       canon = g_build_filename (cwd, filename, NULL);
199       g_free (cwd);
200     }
201   else
202     canon = g_strdup (filename);
203
204   start = (char *)g_path_skip_root (canon);
205
206   if (start == NULL)
207     {
208       /* This shouldn't really happen, as g_get_current_dir() should
209          return an absolute pathname, but bug 573843 shows this is
210          not always happening */
211       g_free (canon);
212       return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
213     }
214   
215   /* POSIX allows double slashes at the start to
216    * mean something special (as does windows too).
217    * So, "//" != "/", but more than two slashes
218    * is treated as "/".
219    */
220   i = 0;
221   for (p = start - 1;
222        (p >= canon) &&
223          G_IS_DIR_SEPARATOR (*p);
224        p--)
225     i++;
226   if (i > 2)
227     {
228       i -= 1;
229       start -= i;
230       memmove (start, start+i, strlen (start+i)+1);
231     }
232   
233   p = start;
234   while (*p != 0)
235     {
236       if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
237         {
238           memmove (p, p+1, strlen (p+1)+1);
239         }
240       else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
241         {
242           q = p + 2;
243           /* Skip previous separator */
244           p = p - 2;
245           if (p < start)
246             p = start;
247           while (p > start && !G_IS_DIR_SEPARATOR (*p))
248             p--;
249           if (G_IS_DIR_SEPARATOR (*p))
250             *p++ = G_DIR_SEPARATOR;
251           memmove (p, q, strlen (q)+1);
252         }
253       else
254         {
255           /* Skip until next separator */
256           while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
257             p++;
258           
259           if (*p != 0)
260             {
261               /* Canonicalize one separator */
262               *p++ = G_DIR_SEPARATOR;
263             }
264         }
265
266       /* Remove additional separators */
267       q = p;
268       while (*q && G_IS_DIR_SEPARATOR (*q))
269         q++;
270
271       if (p != q)
272         memmove (p, q, strlen (q)+1);
273     }
274
275   /* Remove trailing slashes */
276   if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
277     *(p-1) = 0;
278   
279   return canon;
280 }
281
282 GFile *
283 _g_local_file_new (const char *filename)
284 {
285   GLocalFile *local;
286
287   local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
288   local->filename = canonicalize_filename (filename);
289   
290   return G_FILE (local);
291 }
292
293 static gboolean
294 g_local_file_is_native (GFile *file)
295 {
296   return TRUE;
297 }
298
299 static gboolean
300 g_local_file_has_uri_scheme (GFile      *file,
301                              const char *uri_scheme)
302 {
303   return g_ascii_strcasecmp (uri_scheme, "file") == 0;
304 }
305
306 static char *
307 g_local_file_get_uri_scheme (GFile *file)
308 {
309   return g_strdup ("file");
310 }
311
312 static char *
313 g_local_file_get_basename (GFile *file)
314 {
315   return g_path_get_basename (G_LOCAL_FILE (file)->filename);
316 }
317
318 static char *
319 g_local_file_get_path (GFile *file)
320 {
321   return g_strdup (G_LOCAL_FILE (file)->filename);
322 }
323
324 static char *
325 g_local_file_get_uri (GFile *file)
326 {
327   return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
328 }
329
330 static gboolean
331 get_filename_charset (const gchar **filename_charset)
332 {
333   const gchar **charsets;
334   gboolean is_utf8;
335   
336   is_utf8 = g_get_filename_charsets (&charsets);
337
338   if (filename_charset)
339     *filename_charset = charsets[0];
340   
341   return is_utf8;
342 }
343
344 static gboolean
345 name_is_valid_for_display (const char *string,
346                            gboolean    is_valid_utf8)
347 {
348   char c;
349
350   if (!is_valid_utf8 &&
351       !g_utf8_validate (string, -1, NULL))
352     return FALSE;
353
354   while ((c = *string++) != 0)
355     {
356       if (g_ascii_iscntrl (c))
357         return FALSE;
358     }
359
360   return TRUE;
361 }
362
363 static char *
364 g_local_file_get_parse_name (GFile *file)
365 {
366   const char *filename;
367   char *parse_name;
368   const gchar *charset;
369   char *utf8_filename;
370   char *roundtripped_filename;
371   gboolean free_utf8_filename;
372   gboolean is_valid_utf8;
373   char *escaped_path;
374   
375   filename = G_LOCAL_FILE (file)->filename;
376   if (get_filename_charset (&charset))
377     {
378       utf8_filename = (char *)filename;
379       free_utf8_filename = FALSE;
380       is_valid_utf8 = FALSE; /* Can't guarantee this */
381     }
382   else
383     {
384       utf8_filename = g_convert (filename, -1, 
385                                  "UTF-8", charset, NULL, NULL, NULL);
386       free_utf8_filename = TRUE;
387       is_valid_utf8 = TRUE;
388
389       if (utf8_filename != NULL)
390         {
391           /* Make sure we can roundtrip: */
392           roundtripped_filename = g_convert (utf8_filename, -1,
393                                              charset, "UTF-8", NULL, NULL, NULL);
394           
395           if (roundtripped_filename == NULL ||
396               strcmp (filename, roundtripped_filename) != 0)
397             {
398               g_free (utf8_filename);
399               utf8_filename = NULL;
400             }
401
402           g_free (roundtripped_filename);
403         }
404     }
405
406   if (utf8_filename != NULL &&
407       name_is_valid_for_display (utf8_filename, is_valid_utf8))
408     {
409       if (free_utf8_filename)
410         parse_name = utf8_filename;
411       else
412         parse_name = g_strdup (utf8_filename);
413     }
414   else
415     {
416 #ifdef G_OS_WIN32
417       char *dup_filename, *p, *backslash;
418
419       /* Turn backslashes into forward slashes like
420        * g_filename_to_uri() would do (but we can't use that because
421        * it doesn't output IRIs).
422        */
423       dup_filename = g_strdup (filename);
424       filename = p = dup_filename;
425
426       while ((backslash = strchr (p, '\\')) != NULL)
427         {
428           *backslash = '/';
429           p = backslash + 1;
430         }
431 #endif
432
433       escaped_path = g_uri_escape_string (filename,
434                                           G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
435                                           TRUE);
436       parse_name = g_strconcat ("file://",
437                                 (*escaped_path != '/') ? "/" : "",
438                                 escaped_path,
439                                 NULL);
440       
441       g_free (escaped_path);
442 #ifdef G_OS_WIN32
443       g_free (dup_filename);
444 #endif
445       if (free_utf8_filename)
446         g_free (utf8_filename);
447     }
448   
449   return parse_name;
450 }
451
452 static GFile *
453 g_local_file_get_parent (GFile *file)
454 {
455   GLocalFile *local = G_LOCAL_FILE (file);
456   const char *non_root;
457   char *dirname;
458   GFile *parent;
459
460   /* Check for root */
461   non_root = g_path_skip_root (local->filename);
462   if (*non_root == 0)
463     return NULL;
464
465   dirname = g_path_get_dirname (local->filename);
466   parent = _g_local_file_new (dirname);
467   g_free (dirname);
468   return parent;
469 }
470
471 static GFile *
472 g_local_file_dup (GFile *file)
473 {
474   GLocalFile *local = G_LOCAL_FILE (file);
475
476   return _g_local_file_new (local->filename);
477 }
478
479 static guint
480 g_local_file_hash (GFile *file)
481 {
482   GLocalFile *local = G_LOCAL_FILE (file);
483   
484   return g_str_hash (local->filename);
485 }
486
487 static gboolean
488 g_local_file_equal (GFile *file1,
489                     GFile *file2)
490 {
491   GLocalFile *local1 = G_LOCAL_FILE (file1);
492   GLocalFile *local2 = G_LOCAL_FILE (file2);
493
494   return g_str_equal (local1->filename, local2->filename);
495 }
496
497 static const char *
498 match_prefix (const char *path, 
499               const char *prefix)
500 {
501   int prefix_len;
502
503   prefix_len = strlen (prefix);
504   if (strncmp (path, prefix, prefix_len) != 0)
505     return NULL;
506   
507   /* Handle the case where prefix is the root, so that
508    * the IS_DIR_SEPRARATOR check below works */
509   if (prefix_len > 0 &&
510       G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
511     prefix_len--;
512   
513   return path + prefix_len;
514 }
515
516 static gboolean
517 g_local_file_prefix_matches (GFile *parent,
518                              GFile *descendant)
519 {
520   GLocalFile *parent_local = G_LOCAL_FILE (parent);
521   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
522   const char *remainder;
523
524   remainder = match_prefix (descendant_local->filename, parent_local->filename);
525   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
526     return TRUE;
527   return FALSE;
528 }
529
530 static char *
531 g_local_file_get_relative_path (GFile *parent,
532                                 GFile *descendant)
533 {
534   GLocalFile *parent_local = G_LOCAL_FILE (parent);
535   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
536   const char *remainder;
537
538   remainder = match_prefix (descendant_local->filename, parent_local->filename);
539   
540   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
541     return g_strdup (remainder + 1);
542   return NULL;
543 }
544
545 static GFile *
546 g_local_file_resolve_relative_path (GFile      *file,
547                                     const char *relative_path)
548 {
549   GLocalFile *local = G_LOCAL_FILE (file);
550   char *filename;
551   GFile *child;
552
553   if (g_path_is_absolute (relative_path))
554     return _g_local_file_new (relative_path);
555   
556   filename = g_build_filename (local->filename, relative_path, NULL);
557   child = _g_local_file_new (filename);
558   g_free (filename);
559   
560   return child;
561 }
562
563 static GFileEnumerator *
564 g_local_file_enumerate_children (GFile                *file,
565                                  const char           *attributes,
566                                  GFileQueryInfoFlags   flags,
567                                  GCancellable         *cancellable,
568                                  GError              **error)
569 {
570   GLocalFile *local = G_LOCAL_FILE (file);
571   return _g_local_file_enumerator_new (local,
572                                        attributes, flags,
573                                        cancellable, error);
574 }
575
576 static GFile *
577 g_local_file_get_child_for_display_name (GFile        *file,
578                                          const char   *display_name,
579                                          GError      **error)
580 {
581   GFile *new_file;
582   char *basename;
583
584   basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
585   if (basename == NULL)
586     {
587       g_set_error (error, G_IO_ERROR,
588                    G_IO_ERROR_INVALID_FILENAME,
589                    _("Invalid filename %s"), display_name);
590       return NULL;
591     }
592
593   new_file = g_file_get_child (file, basename);
594   g_free (basename);
595   
596   return new_file;
597 }
598
599 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
600 static const char *
601 get_fs_type (long f_type)
602 {
603   /* filesystem ids taken from linux manpage */
604   switch (f_type) 
605     {
606     case 0xadf5:
607       return "adfs";
608     case 0x5346414f:
609       return "afs";
610     case 0x0187:
611       return "autofs";
612     case 0xADFF:
613       return "affs";
614     case 0x42465331:
615       return "befs";
616     case 0x1BADFACE:
617       return "bfs";
618     case 0x9123683E:
619       return "btrfs";
620     case 0xFF534D42:
621       return "cifs";
622     case 0x73757245:
623       return "coda";
624     case 0x012FF7B7:
625       return "coh";
626     case 0x28cd3d45:
627       return "cramfs";
628     case 0x1373:
629       return "devfs";
630     case 0x00414A53:
631       return "efs";
632     case 0x137D:
633       return "ext";
634     case 0xEF51:
635       return "ext2";
636     case 0xEF53:
637       return "ext3/ext4";
638     case 0x4244:
639       return "hfs";
640     case 0xF995E849:
641       return "hpfs";
642     case 0x958458f6:
643       return "hugetlbfs";
644     case 0x9660:
645       return "isofs";
646     case 0x72b6:
647       return "jffs2";
648     case 0x3153464a:
649       return "jfs";
650     case 0x137F:
651       return "minix";
652     case 0x138F:
653       return "minix2";
654     case 0x2468:
655       return "minix2";
656     case 0x2478:
657       return "minix22";
658     case 0x4d44:
659       return "msdos";
660     case 0x564c:
661       return "ncp";
662     case 0x6969:
663       return "nfs";
664     case 0x5346544e:
665       return "ntfs";
666     case 0x9fa1:
667       return "openprom";
668     case 0x9fa0:
669       return "proc";
670     case 0x002f:
671       return "qnx4";
672     case 0x52654973:
673       return "reiserfs";
674     case 0x7275:
675       return "romfs";
676     case 0x517B:
677       return "smb";
678     case 0x73717368:
679       return "squashfs";
680     case 0x012FF7B6:
681       return "sysv2";
682     case 0x012FF7B5:
683       return "sysv4";
684     case 0x01021994:
685       return "tmpfs";
686     case 0x15013346:
687       return "udf";
688     case 0x00011954:
689       return "ufs";
690     case 0x9fa2:
691       return "usbdevice";
692     case 0xa501FCF5:
693       return "vxfs";
694     case 0x012FF7B4:
695       return "xenix";
696     case 0x58465342:
697       return "xfs";
698     case 0x012FD16D:
699       return "xiafs";
700     case 0x52345362:
701       return "reiser4";
702     default:
703       return NULL;
704     }
705 }
706 #endif
707
708 #ifndef G_OS_WIN32
709
710 G_LOCK_DEFINE_STATIC(mount_info_hash);
711 static GHashTable *mount_info_hash = NULL;
712 static guint64 mount_info_hash_cache_time = 0;
713
714 typedef enum {
715   MOUNT_INFO_READONLY = 1<<0
716 } MountInfo;
717
718 static gboolean
719 device_equal (gconstpointer v1,
720               gconstpointer v2)
721 {
722   return *(dev_t *)v1 == *(dev_t *)v2;
723 }
724
725 static guint
726 device_hash (gconstpointer v)
727 {
728   return (guint) *(dev_t *)v;
729 }
730
731 static void
732 get_mount_info (GFileInfo             *fs_info,
733                 const char            *path,
734                 GFileAttributeMatcher *matcher)
735 {
736   GStatBuf buf;
737   gboolean got_info;
738   gpointer info_as_ptr;
739   guint mount_info;
740   char *mountpoint;
741   dev_t *dev;
742   GUnixMountEntry *mount;
743   guint64 cache_time;
744
745   if (g_lstat (path, &buf) != 0)
746     return;
747
748   G_LOCK (mount_info_hash);
749
750   if (mount_info_hash == NULL)
751     mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
752                                              g_free, NULL);
753
754
755   if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
756     g_hash_table_remove_all (mount_info_hash);
757   
758   got_info = g_hash_table_lookup_extended (mount_info_hash,
759                                            &buf.st_dev,
760                                            NULL,
761                                            &info_as_ptr);
762   
763   G_UNLOCK (mount_info_hash);
764   
765   mount_info = GPOINTER_TO_UINT (info_as_ptr);
766   
767   if (!got_info)
768     {
769       mount_info = 0;
770
771       mountpoint = find_mountpoint_for (path, buf.st_dev);
772       if (mountpoint == NULL)
773         mountpoint = g_strdup ("/");
774
775       mount = g_unix_mount_at (mountpoint, &cache_time);
776       if (mount)
777         {
778           if (g_unix_mount_is_readonly (mount))
779             mount_info |= MOUNT_INFO_READONLY;
780           
781           g_unix_mount_free (mount);
782         }
783
784       g_free (mountpoint);
785
786       dev = g_new0 (dev_t, 1);
787       *dev = buf.st_dev;
788       
789       G_LOCK (mount_info_hash);
790       mount_info_hash_cache_time = cache_time;
791       g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
792       G_UNLOCK (mount_info_hash);
793     }
794
795   if (mount_info & MOUNT_INFO_READONLY)
796     g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
797 }
798
799 #endif
800
801 #ifdef G_OS_WIN32
802
803 static gboolean
804 is_xp_or_later (void)
805 {
806   static int result = -1;
807
808   if (result == -1)
809     {
810 #ifndef _MSC_VER    
811       OSVERSIONINFOEX ver_info = {0};
812       DWORDLONG cond_mask = 0;
813       int op = VER_GREATER_EQUAL;
814
815       ver_info.dwOSVersionInfoSize = sizeof ver_info;
816       ver_info.dwMajorVersion = 5;
817       ver_info.dwMinorVersion = 1;
818
819       VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
820       VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
821
822       result = VerifyVersionInfo (&ver_info,
823                                   VER_MAJORVERSION | VER_MINORVERSION, 
824                                   cond_mask) != 0;
825 #else
826       result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;  
827 #endif
828     }
829
830   return result;
831 }
832
833 static wchar_t *
834 get_volume_for_path (const char *path)
835 {
836   long len;
837   wchar_t *wpath;
838   wchar_t *result;
839
840   wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
841   result = g_new (wchar_t, MAX_PATH);
842
843   if (!GetVolumePathNameW (wpath, result, MAX_PATH))
844     {
845       char *msg = g_win32_error_message (GetLastError ());
846       g_critical ("GetVolumePathName failed: %s", msg);
847       g_free (msg);
848       g_free (result);
849       g_free (wpath);
850       return NULL;
851     }
852
853   len = wcslen (result);
854   if (len > 0 && result[len-1] != L'\\')
855     {
856       result = g_renew (wchar_t, result, len + 2);
857       result[len] = L'\\';
858       result[len + 1] = 0;
859     }
860
861   g_free (wpath);
862   return result;
863 }
864
865 static char *
866 find_mountpoint_for (const char *file, dev_t dev)
867 {
868   wchar_t *wpath;
869   char *utf8_path;
870
871   wpath = get_volume_for_path (file);
872   if (!wpath)
873     return NULL;
874
875   utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
876
877   g_free (wpath);
878   return utf8_path;
879 }
880
881 static void
882 get_filesystem_readonly (GFileInfo  *info,
883                          const char *path)
884 {
885   wchar_t *rootdir;
886
887   rootdir = get_volume_for_path (path);
888
889   if (rootdir)
890     {
891       if (is_xp_or_later ())
892         {
893           DWORD flags;
894           if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
895             g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
896                                                (flags & FILE_READ_ONLY_VOLUME) != 0);
897         }
898       else
899         {
900           if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
901             g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
902         }
903     }
904
905   g_free (rootdir);
906 }
907
908 #endif /* G_OS_WIN32 */
909
910 static GFileInfo *
911 g_local_file_query_filesystem_info (GFile         *file,
912                                     const char    *attributes,
913                                     GCancellable  *cancellable,
914                                     GError       **error)
915 {
916   GLocalFile *local = G_LOCAL_FILE (file);
917   GFileInfo *info;
918   int statfs_result = 0;
919   gboolean no_size;
920 #ifndef G_OS_WIN32
921   const char *fstype;
922 #ifdef USE_STATFS
923   guint64 block_size;
924   struct statfs statfs_buffer;
925 #elif defined(USE_STATVFS)
926   guint64 block_size;
927   struct statvfs statfs_buffer;
928 #endif /* USE_STATFS */
929 #endif /* G_OS_WIN32 */
930   GFileAttributeMatcher *attribute_matcher;
931         
932   no_size = FALSE;
933   
934 #ifdef USE_STATFS
935   
936 #if STATFS_ARGS == 2
937   statfs_result = statfs (local->filename, &statfs_buffer);
938 #elif STATFS_ARGS == 4
939   statfs_result = statfs (local->filename, &statfs_buffer,
940                           sizeof (statfs_buffer), 0);
941 #endif /* STATFS_ARGS == 2 */
942   block_size = statfs_buffer.f_bsize;
943   
944   /* Many backends can't report free size (for instance the gvfs fuse
945      backend for backend not supporting this), and set f_bfree to 0,
946      but it can be 0 for real too. We treat the available == 0 and
947      free == 0 case as "both of these are invalid".
948    */
949 #ifndef G_OS_WIN32
950   if (statfs_result == 0 &&
951       statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
952     no_size = TRUE;
953 #endif /* G_OS_WIN32 */
954   
955 #elif defined(USE_STATVFS)
956   statfs_result = statvfs (local->filename, &statfs_buffer);
957   block_size = statfs_buffer.f_frsize; 
958 #endif /* USE_STATFS */
959
960   if (statfs_result == -1)
961     {
962       int errsv = errno;
963
964       g_set_error (error, G_IO_ERROR,
965                    g_io_error_from_errno (errsv),
966                    _("Error getting filesystem info: %s"),
967                    g_strerror (errsv));
968       return NULL;
969     }
970
971   info = g_file_info_new ();
972
973   attribute_matcher = g_file_attribute_matcher_new (attributes);
974   
975   if (!no_size &&
976       g_file_attribute_matcher_matches (attribute_matcher,
977                                         G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
978     {
979 #ifdef G_OS_WIN32
980       gchar *localdir = g_path_get_dirname (local->filename);
981       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
982       ULARGE_INTEGER li;
983       
984       g_free (localdir);
985       if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
986         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
987       g_free (wdirname);
988 #else
989 #if defined(USE_STATFS) || defined(USE_STATVFS)
990       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
991 #endif
992 #endif
993     }
994   if (!no_size &&
995       g_file_attribute_matcher_matches (attribute_matcher,
996                                         G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
997     {
998 #ifdef G_OS_WIN32
999       gchar *localdir = g_path_get_dirname (local->filename);
1000       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1001       ULARGE_INTEGER li;
1002       
1003       g_free (localdir);
1004       if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1005         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,  (guint64)li.QuadPart);
1006       g_free (wdirname);
1007 #else
1008 #if defined(USE_STATFS) || defined(USE_STATVFS)
1009       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1010 #endif
1011 #endif /* G_OS_WIN32 */
1012     }
1013
1014   if (!no_size &&
1015       g_file_attribute_matcher_matches (attribute_matcher,
1016                                         G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1017     {
1018 #ifdef G_OS_WIN32
1019       gchar *localdir = g_path_get_dirname (local->filename);
1020       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1021       ULARGE_INTEGER li_free;
1022       ULARGE_INTEGER li_total;
1023
1024       g_free (localdir);
1025       if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1026         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED,  (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1027       g_free (wdirname);
1028 #else
1029       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1030 #endif /* G_OS_WIN32 */
1031     }
1032
1033 #ifndef G_OS_WIN32
1034 #ifdef USE_STATFS
1035 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1036   fstype = g_strdup (statfs_buffer.f_fstypename);
1037 #else
1038   fstype = get_fs_type (statfs_buffer.f_type);
1039 #endif
1040
1041 #elif defined(USE_STATVFS)
1042 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1043   fstype = g_strdup (statfs_buffer.f_fstypename);
1044 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1045   fstype = g_strdup (statfs_buffer.f_basetype);
1046 #else
1047   fstype = NULL;
1048 #endif
1049 #endif /* USE_STATFS */
1050
1051   if (fstype &&
1052       g_file_attribute_matcher_matches (attribute_matcher,
1053                                         G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1054     g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1055 #endif /* G_OS_WIN32 */
1056
1057   if (g_file_attribute_matcher_matches (attribute_matcher,
1058                                         G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1059     {
1060 #ifdef G_OS_WIN32
1061       get_filesystem_readonly (info, local->filename);
1062 #else
1063       get_mount_info (info, local->filename, attribute_matcher);
1064 #endif /* G_OS_WIN32 */
1065     }
1066   
1067   g_file_attribute_matcher_unref (attribute_matcher);
1068   
1069   return info;
1070 }
1071
1072 static GMount *
1073 g_local_file_find_enclosing_mount (GFile         *file,
1074                                    GCancellable  *cancellable,
1075                                    GError       **error)
1076 {
1077   GLocalFile *local = G_LOCAL_FILE (file);
1078   GStatBuf buf;
1079   char *mountpoint;
1080   GMount *mount;
1081
1082   if (g_lstat (local->filename, &buf) != 0)
1083     {
1084       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1085                       /* Translators: This is an error message when trying to
1086                        * find the enclosing (user visible) mount of a file, but
1087                        * none exists. */
1088                       _("Containing mount does not exist"));
1089       return NULL;
1090     }
1091
1092   mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1093   if (mountpoint == NULL)
1094     {
1095       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1096                       /* Translators: This is an error message when trying to
1097                        * find the enclosing (user visible) mount of a file, but
1098                        * none exists. */
1099                       _("Containing mount does not exist"));
1100       return NULL;
1101     }
1102
1103   mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1104   g_free (mountpoint);
1105   if (mount)
1106     return mount;
1107
1108   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1109                   /* Translators: This is an error message when trying to find
1110                    * the enclosing (user visible) mount of a file, but none
1111                    * exists. */
1112                   _("Containing mount does not exist"));
1113   return NULL;
1114 }
1115
1116 static GFile *
1117 g_local_file_set_display_name (GFile         *file,
1118                                const char    *display_name,
1119                                GCancellable  *cancellable,
1120                                GError       **error)
1121 {
1122   GLocalFile *local, *new_local;
1123   GFile *new_file, *parent;
1124   GStatBuf statbuf;
1125   GVfsClass *class;
1126   GVfs *vfs;
1127   int errsv;
1128
1129   parent = g_file_get_parent (file);
1130   if (parent == NULL)
1131     {
1132       g_set_error_literal (error, G_IO_ERROR,
1133                            G_IO_ERROR_FAILED,
1134                            _("Can't rename root directory"));
1135       return NULL;
1136     }
1137   
1138   new_file = g_file_get_child_for_display_name (parent, display_name, error);
1139   g_object_unref (parent);
1140   
1141   if (new_file == NULL)
1142     return NULL;
1143   local = G_LOCAL_FILE (file);
1144   new_local = G_LOCAL_FILE (new_file);
1145
1146   if (g_lstat (new_local->filename, &statbuf) == -1) 
1147     {
1148       errsv = errno;
1149
1150       if (errsv != ENOENT)
1151         {
1152           g_set_error (error, G_IO_ERROR,
1153                        g_io_error_from_errno (errsv),
1154                        _("Error renaming file: %s"),
1155                        g_strerror (errsv));
1156           return NULL;
1157         }
1158     }
1159   else
1160     {
1161       g_set_error_literal (error, G_IO_ERROR,
1162                            G_IO_ERROR_EXISTS,
1163                            _("Can't rename file, filename already exists"));
1164       return NULL;
1165     }
1166
1167   if (g_rename (local->filename, new_local->filename) == -1)
1168     {
1169       errsv = errno;
1170
1171       if (errsv == EINVAL)
1172         /* We can't get a rename file into itself error herer,
1173            so this must be an invalid filename, on e.g. FAT */
1174         g_set_error_literal (error, G_IO_ERROR,
1175                              G_IO_ERROR_INVALID_FILENAME,
1176                              _("Invalid filename"));
1177       else
1178         g_set_error (error, G_IO_ERROR,
1179                      g_io_error_from_errno (errsv),
1180                      _("Error renaming file: %s"),
1181                      g_strerror (errsv));
1182       g_object_unref (new_file);
1183       return NULL;
1184     }
1185
1186   vfs = g_vfs_get_default ();
1187   class = G_VFS_GET_CLASS (vfs);
1188   if (class->local_file_moved)
1189     class->local_file_moved (vfs, local->filename, new_local->filename);
1190
1191   return new_file;
1192 }
1193
1194 static GFileInfo *
1195 g_local_file_query_info (GFile                *file,
1196                          const char           *attributes,
1197                          GFileQueryInfoFlags   flags,
1198                          GCancellable         *cancellable,
1199                          GError              **error)
1200 {
1201   GLocalFile *local = G_LOCAL_FILE (file);
1202   GFileInfo *info;
1203   GFileAttributeMatcher *matcher;
1204   char *basename, *dirname;
1205   GLocalParentFileInfo parent_info;
1206
1207   matcher = g_file_attribute_matcher_new (attributes);
1208   
1209   basename = g_path_get_basename (local->filename);
1210   
1211   dirname = g_path_get_dirname (local->filename);
1212   _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1213   g_free (dirname);
1214   
1215   info = _g_local_file_info_get (basename, local->filename,
1216                                  matcher, flags, &parent_info,
1217                                  error);
1218   
1219
1220   _g_local_file_info_free_parent_info (&parent_info);
1221   g_free (basename);
1222
1223   g_file_attribute_matcher_unref (matcher);
1224
1225   return info;
1226 }
1227
1228 static GFileAttributeInfoList *
1229 g_local_file_query_settable_attributes (GFile         *file,
1230                                         GCancellable  *cancellable,
1231                                         GError       **error)
1232 {
1233   return g_file_attribute_info_list_ref (local_writable_attributes);
1234 }
1235
1236 static GFileAttributeInfoList *
1237 g_local_file_query_writable_namespaces (GFile         *file,
1238                                         GCancellable  *cancellable,
1239                                         GError       **error)
1240 {
1241   GFileAttributeInfoList *list;
1242   GVfsClass *class;
1243   GVfs *vfs;
1244
1245   if (g_once_init_enter (&local_writable_namespaces))
1246     {
1247       /* Writable namespaces: */
1248
1249       list = g_file_attribute_info_list_new ();
1250
1251 #ifdef HAVE_XATTR
1252       g_file_attribute_info_list_add (list,
1253                                       "xattr",
1254                                       G_FILE_ATTRIBUTE_TYPE_STRING,
1255                                       G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1256                                       G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1257       g_file_attribute_info_list_add (list,
1258                                       "xattr-sys",
1259                                       G_FILE_ATTRIBUTE_TYPE_STRING,
1260                                       G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1261 #endif
1262
1263       vfs = g_vfs_get_default ();
1264       class = G_VFS_GET_CLASS (vfs);
1265       if (class->add_writable_namespaces)
1266         class->add_writable_namespaces (vfs, list);
1267
1268       g_once_init_leave (&local_writable_namespaces, (gsize)list);
1269     }
1270   list = (GFileAttributeInfoList *)local_writable_namespaces;
1271
1272   return g_file_attribute_info_list_ref (list);
1273 }
1274
1275 static gboolean
1276 g_local_file_set_attribute (GFile                *file,
1277                             const char           *attribute,
1278                             GFileAttributeType    type,
1279                             gpointer              value_p,
1280                             GFileQueryInfoFlags   flags,
1281                             GCancellable         *cancellable,
1282                             GError              **error)
1283 {
1284   GLocalFile *local = G_LOCAL_FILE (file);
1285
1286   return _g_local_file_info_set_attribute (local->filename,
1287                                            attribute,
1288                                            type,
1289                                            value_p,
1290                                            flags,
1291                                            cancellable,
1292                                            error);
1293 }
1294
1295 static gboolean
1296 g_local_file_set_attributes_from_info (GFile                *file,
1297                                        GFileInfo            *info,
1298                                        GFileQueryInfoFlags   flags,
1299                                        GCancellable         *cancellable,
1300                                        GError              **error)
1301 {
1302   GLocalFile *local = G_LOCAL_FILE (file);
1303   int res, chained_res;
1304   GFileIface *default_iface;
1305
1306   res = _g_local_file_info_set_attributes (local->filename,
1307                                            info, flags, 
1308                                            cancellable,
1309                                            error);
1310
1311   if (!res)
1312     error = NULL; /* Don't write over error if further errors */
1313
1314   default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1315
1316   chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1317   
1318   return res && chained_res;
1319 }
1320
1321 static GFileInputStream *
1322 g_local_file_read (GFile         *file,
1323                    GCancellable  *cancellable,
1324                    GError       **error)
1325 {
1326   GLocalFile *local = G_LOCAL_FILE (file);
1327   int fd, ret;
1328   GLocalFileStat buf;
1329   
1330   fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1331   if (fd == -1)
1332     {
1333       int errsv = errno;
1334
1335 #ifdef G_OS_WIN32
1336       if (errsv == EACCES)
1337         {
1338           ret = _stati64 (local->filename, &buf);
1339           if (ret == 0 && S_ISDIR (buf.st_mode))
1340             {
1341               g_set_error_literal (error, G_IO_ERROR,
1342                                    G_IO_ERROR_IS_DIRECTORY,
1343                                    _("Can't open directory"));
1344               return NULL;
1345             }
1346         }
1347 #endif
1348
1349       g_set_error (error, G_IO_ERROR,
1350                    g_io_error_from_errno (errsv),
1351                    _("Error opening file: %s"),
1352                    g_strerror (errsv));
1353       return NULL;
1354     }
1355
1356 #ifdef G_OS_WIN32
1357   ret = _fstati64 (fd, &buf);
1358 #else
1359   ret = fstat (fd, &buf);
1360 #endif
1361
1362   if (ret == 0 && S_ISDIR (buf.st_mode))
1363     {
1364       close (fd);
1365       g_set_error_literal (error, G_IO_ERROR,
1366                            G_IO_ERROR_IS_DIRECTORY,
1367                            _("Can't open directory"));
1368       return NULL;
1369     }
1370   
1371   return _g_local_file_input_stream_new (fd);
1372 }
1373
1374 static GFileOutputStream *
1375 g_local_file_append_to (GFile             *file,
1376                         GFileCreateFlags   flags,
1377                         GCancellable      *cancellable,
1378                         GError           **error)
1379 {
1380   return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1381                                              flags, cancellable, error);
1382 }
1383
1384 static GFileOutputStream *
1385 g_local_file_create (GFile             *file,
1386                      GFileCreateFlags   flags,
1387                      GCancellable      *cancellable,
1388                      GError           **error)
1389 {
1390   return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1391                                              FALSE,
1392                                              flags, cancellable, error);
1393 }
1394
1395 static GFileOutputStream *
1396 g_local_file_replace (GFile             *file,
1397                       const char        *etag,
1398                       gboolean           make_backup,
1399                       GFileCreateFlags   flags,
1400                       GCancellable      *cancellable,
1401                       GError           **error)
1402 {
1403   return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1404                                               FALSE,
1405                                               etag, make_backup, flags,
1406                                               cancellable, error);
1407 }
1408
1409 static GFileIOStream *
1410 g_local_file_open_readwrite (GFile                      *file,
1411                              GCancellable               *cancellable,
1412                              GError                    **error)
1413 {
1414   GFileOutputStream *output;
1415   GFileIOStream *res;
1416
1417   output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1418                                              TRUE,
1419                                              cancellable, error);
1420   if (output == NULL)
1421     return NULL;
1422
1423   res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1424   g_object_unref (output);
1425   return res;
1426 }
1427
1428 static GFileIOStream *
1429 g_local_file_create_readwrite (GFile                      *file,
1430                                GFileCreateFlags            flags,
1431                                GCancellable               *cancellable,
1432                                GError                    **error)
1433 {
1434   GFileOutputStream *output;
1435   GFileIOStream *res;
1436
1437   output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1438                                                TRUE, flags,
1439                                                cancellable, error);
1440   if (output == NULL)
1441     return NULL;
1442
1443   res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1444   g_object_unref (output);
1445   return res;
1446 }
1447
1448 static GFileIOStream *
1449 g_local_file_replace_readwrite (GFile                      *file,
1450                                 const char                 *etag,
1451                                 gboolean                    make_backup,
1452                                 GFileCreateFlags            flags,
1453                                 GCancellable               *cancellable,
1454                                 GError                    **error)
1455 {
1456   GFileOutputStream *output;
1457   GFileIOStream *res;
1458
1459   output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1460                                                 TRUE,
1461                                                 etag, make_backup, flags,
1462                                                 cancellable, error);
1463   if (output == NULL)
1464     return NULL;
1465
1466   res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1467   g_object_unref (output);
1468   return res;
1469 }
1470
1471 static gboolean
1472 g_local_file_delete (GFile         *file,
1473                      GCancellable  *cancellable,
1474                      GError       **error)
1475 {
1476   GLocalFile *local = G_LOCAL_FILE (file);
1477   GVfsClass *class;
1478   GVfs *vfs;
1479
1480   if (g_remove (local->filename) == -1)
1481     {
1482       int errsv = errno;
1483
1484       /* Posix allows EEXIST too, but the more sane error
1485          is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1486          expects */
1487       if (errsv == EEXIST)
1488         errsv = ENOTEMPTY;
1489
1490       g_set_error (error, G_IO_ERROR,
1491                    g_io_error_from_errno (errsv),
1492                    _("Error removing file: %s"),
1493                    g_strerror (errsv));
1494       return FALSE;
1495     }
1496
1497   vfs = g_vfs_get_default ();
1498   class = G_VFS_GET_CLASS (vfs);
1499   if (class->local_file_removed)
1500     class->local_file_removed (vfs, local->filename);
1501
1502   return TRUE;
1503 }
1504
1505 #ifndef G_OS_WIN32
1506
1507 static char *
1508 strip_trailing_slashes (const char *path)
1509 {
1510   char *path_copy;
1511   int len;
1512
1513   path_copy = g_strdup (path);
1514   len = strlen (path_copy);
1515   while (len > 1 && path_copy[len-1] == '/')
1516     path_copy[--len] = 0;
1517
1518   return path_copy;
1519  }
1520
1521 static char *
1522 expand_symlink (const char *link)
1523 {
1524   char *resolved, *canonical, *parent, *link2;
1525   char symlink_value[4096];
1526 #ifdef G_OS_WIN32
1527 #else
1528   ssize_t res;
1529 #endif
1530   
1531 #ifdef G_OS_WIN32
1532 #else
1533   res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1534   
1535   if (res == -1)
1536     return g_strdup (link);
1537   symlink_value[res] = 0;
1538 #endif
1539   
1540   if (g_path_is_absolute (symlink_value))
1541     return canonicalize_filename (symlink_value);
1542   else
1543     {
1544       link2 = strip_trailing_slashes (link);
1545       parent = g_path_get_dirname (link2);
1546       g_free (link2);
1547       
1548       resolved = g_build_filename (parent, symlink_value, NULL);
1549       g_free (parent);
1550       
1551       canonical = canonicalize_filename (resolved);
1552       
1553       g_free (resolved);
1554
1555       return canonical;
1556     }
1557 }
1558
1559 static char *
1560 get_parent (const char *path, 
1561             dev_t      *parent_dev)
1562 {
1563   char *parent, *tmp;
1564   GStatBuf parent_stat;
1565   int num_recursions;
1566   char *path_copy;
1567
1568   path_copy = strip_trailing_slashes (path);
1569   
1570   parent = g_path_get_dirname (path_copy);
1571   if (strcmp (parent, ".") == 0 ||
1572       strcmp (parent, path_copy) == 0)
1573     {
1574       g_free (parent);
1575       g_free (path_copy);
1576       return NULL;
1577     }
1578   g_free (path_copy);
1579
1580   num_recursions = 0;
1581   do {
1582     if (g_lstat (parent, &parent_stat) != 0)
1583       {
1584         g_free (parent);
1585         return NULL;
1586       }
1587     
1588     if (S_ISLNK (parent_stat.st_mode))
1589       {
1590         tmp = parent;
1591         parent = expand_symlink (parent);
1592         g_free (tmp);
1593       }
1594     
1595     num_recursions++;
1596     if (num_recursions > 12)
1597       {
1598         g_free (parent);
1599         return NULL;
1600       }
1601   } while (S_ISLNK (parent_stat.st_mode));
1602
1603   *parent_dev = parent_stat.st_dev;
1604   
1605   return parent;
1606 }
1607
1608 static char *
1609 expand_all_symlinks (const char *path)
1610 {
1611   char *parent, *parent_expanded;
1612   char *basename, *res;
1613   dev_t parent_dev;
1614
1615   parent = get_parent (path, &parent_dev);
1616   if (parent)
1617     {
1618       parent_expanded = expand_all_symlinks (parent);
1619       g_free (parent);
1620       basename = g_path_get_basename (path);
1621       res = g_build_filename (parent_expanded, basename, NULL);
1622       g_free (basename);
1623       g_free (parent_expanded);
1624     }
1625   else
1626     res = g_strdup (path);
1627   
1628   return res;
1629 }
1630
1631 static char *
1632 find_mountpoint_for (const char *file, 
1633                      dev_t       dev)
1634 {
1635   char *dir, *parent;
1636   dev_t dir_dev, parent_dev;
1637
1638   dir = g_strdup (file);
1639   dir_dev = dev;
1640
1641   while (1) 
1642     {
1643       parent = get_parent (dir, &parent_dev);
1644       if (parent == NULL)
1645         return dir;
1646     
1647       if (parent_dev != dir_dev)
1648         {
1649           g_free (parent);
1650           return dir;
1651         }
1652     
1653       g_free (dir);
1654       dir = parent;
1655     }
1656 }
1657
1658 static char *
1659 find_topdir_for (const char *file)
1660 {
1661   char *dir;
1662   dev_t dir_dev;
1663
1664   dir = get_parent (file, &dir_dev);
1665   if (dir == NULL)
1666     return NULL;
1667
1668   return find_mountpoint_for (dir, dir_dev);
1669 }
1670
1671 static char *
1672 get_unique_filename (const char *basename, 
1673                      int         id)
1674 {
1675   const char *dot;
1676       
1677   if (id == 1)
1678     return g_strdup (basename);
1679
1680   dot = strchr (basename, '.');
1681   if (dot)
1682     return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1683   else
1684     return g_strdup_printf ("%s.%d", basename, id);
1685 }
1686
1687 static gboolean
1688 path_has_prefix (const char *path, 
1689                  const char *prefix)
1690 {
1691   int prefix_len;
1692
1693   if (prefix == NULL)
1694     return TRUE;
1695
1696   prefix_len = strlen (prefix);
1697   
1698   if (strncmp (path, prefix, prefix_len) == 0 &&
1699       (prefix_len == 0 || /* empty prefix always matches */
1700        prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1701        path[prefix_len] == 0 ||
1702        path[prefix_len] == '/'))
1703     return TRUE;
1704   
1705   return FALSE;
1706 }
1707
1708 static char *
1709 try_make_relative (const char *path, 
1710                    const char *base)
1711 {
1712   char *path2, *base2;
1713   char *relative;
1714
1715   path2 = expand_all_symlinks (path);
1716   base2 = expand_all_symlinks (base);
1717
1718   relative = NULL;
1719   if (path_has_prefix (path2, base2))
1720     {
1721       relative = path2 + strlen (base2);
1722       while (*relative == '/')
1723         relative ++;
1724       relative = g_strdup (relative);
1725     }
1726   g_free (path2);
1727   g_free (base2);
1728
1729   if (relative)
1730     return relative;
1731   
1732   /* Failed, use abs path */
1733   return g_strdup (path);
1734 }
1735
1736 gboolean
1737 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1738 {
1739   static gsize home_dev_set = 0;
1740   static dev_t home_dev;
1741   char *topdir, *globaldir, *trashdir, *tmpname;
1742   uid_t uid;
1743   char uid_str[32];
1744   GStatBuf global_stat, trash_stat;
1745   gboolean res;
1746
1747   if (g_once_init_enter (&home_dev_set))
1748     {
1749       GStatBuf home_stat;
1750
1751       g_stat (g_get_home_dir (), &home_stat);
1752       home_dev = home_stat.st_dev;
1753       g_once_init_leave (&home_dev_set, 1);
1754     }
1755
1756   /* Assume we can trash to the home */
1757   if (dir_dev == home_dev)
1758     return TRUE;
1759
1760   topdir = find_mountpoint_for (dirname, dir_dev);
1761   if (topdir == NULL)
1762     return FALSE;
1763
1764   globaldir = g_build_filename (topdir, ".Trash", NULL);
1765   if (g_lstat (globaldir, &global_stat) == 0 &&
1766       S_ISDIR (global_stat.st_mode) &&
1767       (global_stat.st_mode & S_ISVTX) != 0)
1768     {
1769       /* got a toplevel sysadmin created dir, assume we
1770        * can trash to it (we should be able to create a dir)
1771        * This fails for the FAT case where the ownership of
1772        * that dir would be wrong though..
1773        */
1774       g_free (globaldir);
1775       g_free (topdir);
1776       return TRUE;
1777     }
1778   g_free (globaldir);
1779
1780   /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1781   uid = geteuid ();
1782   g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1783
1784   tmpname = g_strdup_printf (".Trash-%s", uid_str);
1785   trashdir = g_build_filename (topdir, tmpname, NULL);
1786   g_free (tmpname);
1787
1788   if (g_lstat (trashdir, &trash_stat) == 0)
1789     {
1790       g_free (topdir);
1791       g_free (trashdir);
1792       return S_ISDIR (trash_stat.st_mode) &&
1793              trash_stat.st_uid == uid;
1794     }
1795   g_free (trashdir);
1796
1797   /* User specific trash didn't exist, can we create it? */
1798   res = g_access (topdir, W_OK) == 0;
1799   g_free (topdir);
1800
1801   return res;
1802 }
1803
1804
1805 static gboolean
1806 g_local_file_trash (GFile         *file,
1807                     GCancellable  *cancellable,
1808                     GError       **error)
1809 {
1810   GLocalFile *local = G_LOCAL_FILE (file);
1811   GStatBuf file_stat, home_stat;
1812   const char *homedir;
1813   char *trashdir, *topdir, *infodir, *filesdir;
1814   char *basename, *trashname, *trashfile, *infoname, *infofile;
1815   char *original_name, *original_name_escaped;
1816   int i;
1817   char *data;
1818   gboolean is_homedir_trash;
1819   char delete_time[32];
1820   int fd;
1821   GStatBuf trash_stat, global_stat;
1822   char *dirname, *globaldir;
1823   GVfsClass *class;
1824   GVfs *vfs;
1825
1826   if (g_lstat (local->filename, &file_stat) != 0)
1827     {
1828       int errsv = errno;
1829
1830       g_set_error (error, G_IO_ERROR,
1831                    g_io_error_from_errno (errsv),
1832                    _("Error trashing file: %s"),
1833                    g_strerror (errsv));
1834       return FALSE;
1835     }
1836     
1837   homedir = g_get_home_dir ();
1838   g_stat (homedir, &home_stat);
1839
1840   is_homedir_trash = FALSE;
1841   trashdir = NULL;
1842   if (file_stat.st_dev == home_stat.st_dev)
1843     {
1844       is_homedir_trash = TRUE;
1845       errno = 0;
1846       trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1847       if (g_mkdir_with_parents (trashdir, 0700) < 0)
1848         {
1849           char *display_name;
1850           int errsv = errno;
1851
1852           display_name = g_filename_display_name (trashdir);
1853           g_set_error (error, G_IO_ERROR,
1854                        g_io_error_from_errno (errsv),
1855                        _("Unable to create trash dir %s: %s"),
1856                        display_name, g_strerror (errsv));
1857           g_free (display_name);
1858           g_free (trashdir);
1859           return FALSE;
1860         }
1861       topdir = g_strdup (g_get_user_data_dir ());
1862     }
1863   else
1864     {
1865       uid_t uid;
1866       char uid_str[32];
1867
1868       uid = geteuid ();
1869       g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1870       
1871       topdir = find_topdir_for (local->filename);
1872       if (topdir == NULL)
1873         {
1874           g_set_error_literal (error, G_IO_ERROR,
1875                                G_IO_ERROR_NOT_SUPPORTED,
1876                                _("Unable to find toplevel directory for trash"));
1877           return FALSE;
1878         }
1879       
1880       /* Try looking for global trash dir $topdir/.Trash/$uid */
1881       globaldir = g_build_filename (topdir, ".Trash", NULL);
1882       if (g_lstat (globaldir, &global_stat) == 0 &&
1883           S_ISDIR (global_stat.st_mode) &&
1884           (global_stat.st_mode & S_ISVTX) != 0)
1885         {
1886           trashdir = g_build_filename (globaldir, uid_str, NULL);
1887
1888           if (g_lstat (trashdir, &trash_stat) == 0)
1889             {
1890               if (!S_ISDIR (trash_stat.st_mode) ||
1891                   trash_stat.st_uid != uid)
1892                 {
1893                   /* Not a directory or not owned by user, ignore */
1894                   g_free (trashdir);
1895                   trashdir = NULL;
1896                 }
1897             }
1898           else if (g_mkdir (trashdir, 0700) == -1)
1899             {
1900               g_free (trashdir);
1901               trashdir = NULL;
1902             }
1903         }
1904       g_free (globaldir);
1905
1906       if (trashdir == NULL)
1907         {
1908           gboolean tried_create;
1909           
1910           /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1911           dirname = g_strdup_printf (".Trash-%s", uid_str);
1912           trashdir = g_build_filename (topdir, dirname, NULL);
1913           g_free (dirname);
1914
1915           tried_create = FALSE;
1916
1917         retry:
1918           if (g_lstat (trashdir, &trash_stat) == 0)
1919             {
1920               if (!S_ISDIR (trash_stat.st_mode) ||
1921                   trash_stat.st_uid != uid)
1922                 {
1923                   /* Remove the failed directory */
1924                   if (tried_create)
1925                     g_remove (trashdir);
1926                   
1927                   /* Not a directory or not owned by user, ignore */
1928                   g_free (trashdir);
1929                   trashdir = NULL;
1930                 }
1931             }
1932           else
1933             {
1934               if (!tried_create &&
1935                   g_mkdir (trashdir, 0700) != -1)
1936                 {
1937                   /* Ensure that the created dir has the right uid etc.
1938                      This might fail on e.g. a FAT dir */
1939                   tried_create = TRUE;
1940                   goto retry;
1941                 }
1942               else
1943                 {
1944                   g_free (trashdir);
1945                   trashdir = NULL;
1946                 }
1947             }
1948         }
1949
1950       if (trashdir == NULL)
1951         {
1952           g_free (topdir);
1953           g_set_error_literal (error, G_IO_ERROR,
1954                                G_IO_ERROR_NOT_SUPPORTED,
1955                                _("Unable to find or create trash directory"));
1956           return FALSE;
1957         }
1958     }
1959
1960   /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1961
1962   infodir = g_build_filename (trashdir, "info", NULL);
1963   filesdir = g_build_filename (trashdir, "files", NULL);
1964   g_free (trashdir);
1965
1966   /* Make sure we have the subdirectories */
1967   if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1968       (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1969     {
1970       g_free (topdir);
1971       g_free (infodir);
1972       g_free (filesdir);
1973       g_set_error_literal (error, G_IO_ERROR,
1974                            G_IO_ERROR_NOT_SUPPORTED,
1975                            _("Unable to find or create trash directory"));
1976       return FALSE;
1977     }  
1978
1979   basename = g_path_get_basename (local->filename);
1980   i = 1;
1981   trashname = NULL;
1982   infofile = NULL;
1983   do {
1984     g_free (trashname);
1985     g_free (infofile);
1986     
1987     trashname = get_unique_filename (basename, i++);
1988     infoname = g_strconcat (trashname, ".trashinfo", NULL);
1989     infofile = g_build_filename (infodir, infoname, NULL);
1990     g_free (infoname);
1991
1992     fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
1993   } while (fd == -1 && errno == EEXIST);
1994
1995   g_free (basename);
1996   g_free (infodir);
1997
1998   if (fd == -1)
1999     {
2000       int errsv = errno;
2001
2002       g_free (filesdir);
2003       g_free (topdir);
2004       g_free (trashname);
2005       g_free (infofile);
2006       
2007       g_set_error (error, G_IO_ERROR,
2008                    g_io_error_from_errno (errsv),
2009                    _("Unable to create trashing info file: %s"),
2010                    g_strerror (errsv));
2011       return FALSE;
2012     }
2013
2014   close (fd);
2015
2016   /* TODO: Maybe we should verify that you can delete the file from the trash
2017      before moving it? OTOH, that is hard, as it needs a recursive scan */
2018
2019   trashfile = g_build_filename (filesdir, trashname, NULL);
2020
2021   g_free (filesdir);
2022
2023   if (g_rename (local->filename, trashfile) == -1)
2024     {
2025       int errsv = errno;
2026
2027       g_free (topdir);
2028       g_free (trashname);
2029       g_free (infofile);
2030       g_free (trashfile);
2031
2032       if (errsv == EXDEV)
2033         /* The trash dir was actually on another fs anyway!?
2034            This can happen when the same device is mounted multiple
2035            times, or with bind mounts of the same fs. */
2036         g_set_error (error, G_IO_ERROR,
2037                      G_IO_ERROR_NOT_SUPPORTED,
2038                      _("Unable to trash file: %s"),
2039                      g_strerror (errsv));
2040       else
2041         g_set_error (error, G_IO_ERROR,
2042                      g_io_error_from_errno (errsv),
2043                      _("Unable to trash file: %s"),
2044                      g_strerror (errsv));
2045       return FALSE;
2046     }
2047
2048   vfs = g_vfs_get_default ();
2049   class = G_VFS_GET_CLASS (vfs);
2050   if (class->local_file_moved)
2051     class->local_file_moved (vfs, local->filename, trashfile);
2052
2053   g_free (trashfile);
2054
2055   /* TODO: Do we need to update mtime/atime here after the move? */
2056
2057   /* Use absolute names for homedir */
2058   if (is_homedir_trash)
2059     original_name = g_strdup (local->filename);
2060   else
2061     original_name = try_make_relative (local->filename, topdir);
2062   original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2063   
2064   g_free (original_name);
2065   g_free (topdir);
2066   
2067   {
2068     time_t t;
2069     struct tm now;
2070     t = time (NULL);
2071     localtime_r (&t, &now);
2072     delete_time[0] = 0;
2073     strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
2074   }
2075
2076   data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2077                           original_name_escaped, delete_time);
2078
2079   g_file_set_contents (infofile, data, -1, NULL);
2080   g_free (infofile);
2081   g_free (data);
2082   
2083   g_free (original_name_escaped);
2084   g_free (trashname);
2085   
2086   return TRUE;
2087 }
2088 #else /* G_OS_WIN32 */
2089 gboolean
2090 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2091 {
2092   return FALSE;                 /* XXX ??? */
2093 }
2094
2095 static gboolean
2096 g_local_file_trash (GFile         *file,
2097                     GCancellable  *cancellable,
2098                     GError       **error)
2099 {
2100   GLocalFile *local = G_LOCAL_FILE (file);
2101   SHFILEOPSTRUCTW op = {0};
2102   gboolean success;
2103   wchar_t *wfilename;
2104   long len;
2105
2106   wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2107   /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2108   wfilename = g_renew (wchar_t, wfilename, len + 2);
2109   wfilename[len + 1] = 0;
2110
2111   op.wFunc = FO_DELETE;
2112   op.pFrom = wfilename;
2113   op.fFlags = FOF_ALLOWUNDO;
2114
2115   success = SHFileOperationW (&op) == 0;
2116
2117   if (success && op.fAnyOperationsAborted)
2118     {
2119       if (cancellable && !g_cancellable_is_cancelled (cancellable))
2120         g_cancellable_cancel (cancellable);
2121       g_set_error (error, G_IO_ERROR,
2122                    G_IO_ERROR_CANCELLED,
2123                    _("Unable to trash file: %s"),
2124                    _("Operation was cancelled"));
2125       success = FALSE;
2126     }
2127   else if (!success)
2128     g_set_error (error, G_IO_ERROR,
2129                  G_IO_ERROR_FAILED,
2130                  _("Unable to trash file: %s"),
2131                  _("internal error"));
2132
2133   g_free (wfilename);
2134   return success;
2135 }
2136 #endif /* G_OS_WIN32 */
2137
2138 static gboolean
2139 g_local_file_make_directory (GFile         *file,
2140                              GCancellable  *cancellable,
2141                              GError       **error)
2142 {
2143   GLocalFile *local = G_LOCAL_FILE (file);
2144   
2145   if (g_mkdir (local->filename, 0777) == -1)
2146     {
2147       int errsv = errno;
2148
2149       if (errsv == EINVAL)
2150         /* This must be an invalid filename, on e.g. FAT */
2151         g_set_error_literal (error, G_IO_ERROR,
2152                              G_IO_ERROR_INVALID_FILENAME,
2153                              _("Invalid filename"));
2154       else
2155         g_set_error (error, G_IO_ERROR,
2156                      g_io_error_from_errno (errsv),
2157                      _("Error creating directory: %s"),
2158                      g_strerror (errsv));
2159       return FALSE;
2160     }
2161   
2162   return TRUE;
2163 }
2164
2165 static gboolean
2166 g_local_file_make_symbolic_link (GFile         *file,
2167                                  const char    *symlink_value,
2168                                  GCancellable  *cancellable,
2169                                  GError       **error)
2170 {
2171 #ifdef HAVE_SYMLINK
2172   GLocalFile *local = G_LOCAL_FILE (file);
2173   
2174   if (symlink (symlink_value, local->filename) == -1)
2175     {
2176       int errsv = errno;
2177
2178       if (errsv == EINVAL)
2179         /* This must be an invalid filename, on e.g. FAT */
2180         g_set_error_literal (error, G_IO_ERROR,
2181                              G_IO_ERROR_INVALID_FILENAME,
2182                              _("Invalid filename"));
2183       else if (errsv == EPERM)
2184         g_set_error (error, G_IO_ERROR,
2185                      G_IO_ERROR_NOT_SUPPORTED,
2186                      _("Filesystem does not support symbolic links"));
2187       else
2188         g_set_error (error, G_IO_ERROR,
2189                      g_io_error_from_errno (errsv),
2190                      _("Error making symbolic link: %s"),
2191                      g_strerror (errsv));
2192       return FALSE;
2193     }
2194   return TRUE;
2195 #else
2196   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
2197   return FALSE;
2198 #endif
2199 }
2200
2201
2202 static gboolean
2203 g_local_file_copy (GFile                  *source,
2204                    GFile                  *destination,
2205                    GFileCopyFlags          flags,
2206                    GCancellable           *cancellable,
2207                    GFileProgressCallback   progress_callback,
2208                    gpointer                progress_callback_data,
2209                    GError                **error)
2210 {
2211   /* Fall back to default copy */
2212   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2213   return FALSE;
2214 }
2215
2216 static gboolean
2217 g_local_file_move (GFile                  *source,
2218                    GFile                  *destination,
2219                    GFileCopyFlags          flags,
2220                    GCancellable           *cancellable,
2221                    GFileProgressCallback   progress_callback,
2222                    gpointer                progress_callback_data,
2223                    GError                **error)
2224 {
2225   GLocalFile *local_source, *local_destination;
2226   GStatBuf statbuf;
2227   gboolean destination_exist, source_is_dir;
2228   char *backup_name;
2229   int res;
2230   off_t source_size;
2231   GVfsClass *class;
2232   GVfs *vfs;
2233
2234   if (!G_IS_LOCAL_FILE (source) ||
2235       !G_IS_LOCAL_FILE (destination))
2236     {
2237       /* Fall back to default move */
2238       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2239       return FALSE;
2240     }
2241   
2242   local_source = G_LOCAL_FILE (source);
2243   local_destination = G_LOCAL_FILE (destination);
2244   
2245   res = g_lstat (local_source->filename, &statbuf);
2246   if (res == -1)
2247     {
2248       int errsv = errno;
2249
2250       g_set_error (error, G_IO_ERROR,
2251                    g_io_error_from_errno (errsv),
2252                    _("Error moving file: %s"),
2253                    g_strerror (errsv));
2254       return FALSE;
2255     }
2256
2257   source_is_dir = S_ISDIR (statbuf.st_mode);
2258   source_size = statbuf.st_size;
2259   
2260   destination_exist = FALSE;
2261   res = g_lstat (local_destination->filename, &statbuf);
2262   if (res == 0)
2263     {
2264       destination_exist = TRUE; /* Target file exists */
2265
2266       if (flags & G_FILE_COPY_OVERWRITE)
2267         {
2268           /* Always fail on dirs, even with overwrite */
2269           if (S_ISDIR (statbuf.st_mode))
2270             {
2271               if (source_is_dir)
2272                 g_set_error_literal (error,
2273                                      G_IO_ERROR,
2274                                      G_IO_ERROR_WOULD_MERGE,
2275                                      _("Can't move directory over directory"));
2276               else
2277                 g_set_error_literal (error,
2278                                      G_IO_ERROR,
2279                                      G_IO_ERROR_IS_DIRECTORY,
2280                                      _("Can't copy over directory"));
2281               return FALSE;
2282             }
2283         }
2284       else
2285         {
2286           g_set_error_literal (error,
2287                                G_IO_ERROR,
2288                                G_IO_ERROR_EXISTS,
2289                                _("Target file exists"));
2290           return FALSE;
2291         }
2292     }
2293   
2294   if (flags & G_FILE_COPY_BACKUP && destination_exist)
2295     {
2296       backup_name = g_strconcat (local_destination->filename, "~", NULL);
2297       if (g_rename (local_destination->filename, backup_name) == -1)
2298         {
2299           g_set_error_literal (error,
2300                                G_IO_ERROR,
2301                                G_IO_ERROR_CANT_CREATE_BACKUP,
2302                                _("Backup file creation failed"));
2303           g_free (backup_name);
2304           return FALSE;
2305         }
2306       g_free (backup_name);
2307       destination_exist = FALSE; /* It did, but no more */
2308     }
2309
2310   if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2311     {
2312       /* Source is a dir, destination exists (and is not a dir, because that would have failed
2313          earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2314       res = g_unlink (local_destination->filename);
2315       if (res == -1)
2316         {
2317           int errsv = errno;
2318
2319           g_set_error (error, G_IO_ERROR,
2320                        g_io_error_from_errno (errsv),
2321                        _("Error removing target file: %s"),
2322                        g_strerror (errsv));
2323           return FALSE;
2324         }
2325     }
2326   
2327   if (g_rename (local_source->filename, local_destination->filename) == -1)
2328     {
2329       int errsv = errno;
2330
2331       if (errsv == EXDEV)
2332         /* This will cause the fallback code to run */
2333         g_set_error_literal (error, G_IO_ERROR,
2334                              G_IO_ERROR_NOT_SUPPORTED,
2335                              _("Move between mounts not supported"));
2336       else if (errsv == EINVAL)
2337         /* This must be an invalid filename, on e.g. FAT, or
2338            we're trying to move the file into itself...
2339            We return invalid filename for both... */
2340         g_set_error_literal (error, G_IO_ERROR,
2341                              G_IO_ERROR_INVALID_FILENAME,
2342                              _("Invalid filename"));
2343       else
2344         g_set_error (error, G_IO_ERROR,
2345                      g_io_error_from_errno (errsv),
2346                      _("Error moving file: %s"),
2347                      g_strerror (errsv));
2348       return FALSE;
2349     }
2350
2351   vfs = g_vfs_get_default ();
2352   class = G_VFS_GET_CLASS (vfs);
2353   if (class->local_file_moved)
2354     class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2355
2356   /* Make sure we send full copied size */
2357   if (progress_callback)
2358     progress_callback (source_size, source_size, progress_callback_data);
2359   
2360   return TRUE;
2361 }
2362
2363 static GFileMonitor*
2364 g_local_file_monitor_dir (GFile             *file,
2365                           GFileMonitorFlags  flags,
2366                           GCancellable      *cancellable,
2367                           GError           **error)
2368 {
2369   GLocalFile* local_file = G_LOCAL_FILE(file);
2370   return _g_local_directory_monitor_new (local_file->filename, flags, error);
2371 }
2372
2373 static GFileMonitor*
2374 g_local_file_monitor_file (GFile             *file,
2375                            GFileMonitorFlags  flags,
2376                            GCancellable      *cancellable,
2377                            GError           **error)
2378 {
2379   GLocalFile* local_file = G_LOCAL_FILE(file);
2380   return _g_local_file_monitor_new (local_file->filename, flags, error);
2381 }
2382
2383 static void
2384 g_local_file_file_iface_init (GFileIface *iface)
2385 {
2386   iface->dup = g_local_file_dup;
2387   iface->hash = g_local_file_hash;
2388   iface->equal = g_local_file_equal;
2389   iface->is_native = g_local_file_is_native;
2390   iface->has_uri_scheme = g_local_file_has_uri_scheme;
2391   iface->get_uri_scheme = g_local_file_get_uri_scheme;
2392   iface->get_basename = g_local_file_get_basename;
2393   iface->get_path = g_local_file_get_path;
2394   iface->get_uri = g_local_file_get_uri;
2395   iface->get_parse_name = g_local_file_get_parse_name;
2396   iface->get_parent = g_local_file_get_parent;
2397   iface->prefix_matches = g_local_file_prefix_matches;
2398   iface->get_relative_path = g_local_file_get_relative_path;
2399   iface->resolve_relative_path = g_local_file_resolve_relative_path;
2400   iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2401   iface->set_display_name = g_local_file_set_display_name;
2402   iface->enumerate_children = g_local_file_enumerate_children;
2403   iface->query_info = g_local_file_query_info;
2404   iface->query_filesystem_info = g_local_file_query_filesystem_info;
2405   iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2406   iface->query_settable_attributes = g_local_file_query_settable_attributes;
2407   iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2408   iface->set_attribute = g_local_file_set_attribute;
2409   iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2410   iface->read_fn = g_local_file_read;
2411   iface->append_to = g_local_file_append_to;
2412   iface->create = g_local_file_create;
2413   iface->replace = g_local_file_replace;
2414   iface->open_readwrite = g_local_file_open_readwrite;
2415   iface->create_readwrite = g_local_file_create_readwrite;
2416   iface->replace_readwrite = g_local_file_replace_readwrite;
2417   iface->delete_file = g_local_file_delete;
2418   iface->trash = g_local_file_trash;
2419   iface->make_directory = g_local_file_make_directory;
2420   iface->make_symbolic_link = g_local_file_make_symbolic_link;
2421   iface->copy = g_local_file_copy;
2422   iface->move = g_local_file_move;
2423   iface->monitor_dir = g_local_file_monitor_dir;
2424   iface->monitor_file = g_local_file_monitor_file;
2425
2426   iface->supports_thread_contexts = TRUE;
2427 }