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