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