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