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