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