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