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