Add G_FILE_COPY_NO_FALLBACK_FOR_MOVE flag
[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 #include <unistd.h>
31
32 #if HAVE_SYS_STATFS_H
33 #include <sys/statfs.h>
34 #endif
35 #if HAVE_SYS_STATVFS_H
36 #include <sys/statvfs.h>
37 #endif
38 #if HAVE_SYS_VFS_H
39 #include <sys/vfs.h>
40 #elif HAVE_SYS_MOUNT_H
41 #if HAVE_SYS_PARAM_H
42 #include <sys/param.h>
43 #endif
44 #include <sys/mount.h>
45 #endif
46
47 #if defined(HAVE_STATFS) && defined(HAVE_STATVFS)
48 /* Some systems have both statfs and statvfs, pick the
49    most "native" for these */
50 # if defined(sun) && defined(__SVR4)
51    /* on solaris, statfs doesn't even have the
52       f_bavail field */
53 #  define USE_STATVFS
54 # else
55   /* at least on linux, statfs is the actual syscall */
56 #  define USE_STATFS
57 # endif
58
59 #elif defined(HAVE_STATFS)
60
61 # define USE_STATFS
62
63 #elif defined(HAVE_STATVFS)
64
65 # define USE_STATVFS
66
67 #endif
68
69 #include "glocalfile.h"
70 #include "glocalfileinfo.h"
71 #include "glocalfileenumerator.h"
72 #include "glocalfileinputstream.h"
73 #include "glocalfileoutputstream.h"
74 #include "glocaldirectorymonitor.h"
75 #include "glocalfilemonitor.h"
76 #include "gvolumeprivate.h"
77 #include <glib/gstdio.h>
78 #include "glibintl.h"
79
80 #include "gioalias.h"
81
82 static void g_local_file_file_iface_init (GFileIface       *iface);
83
84 static GFileAttributeInfoList *local_writable_attributes = NULL;
85 static GFileAttributeInfoList *local_writable_namespaces = NULL;
86
87 struct _GLocalFile
88 {
89   GObject parent_instance;
90
91   char *filename;
92 };
93
94 #define g_local_file_get_type _g_local_file_get_type
95 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
96                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
97                                                 g_local_file_file_iface_init))
98
99 static char * find_mountpoint_for (const char *file, dev_t dev);
100
101 static void
102 g_local_file_finalize (GObject *object)
103 {
104   GLocalFile *local;
105
106   local = G_LOCAL_FILE (object);
107
108   g_free (local->filename);
109   
110   if (G_OBJECT_CLASS (g_local_file_parent_class)->finalize)
111     (*G_OBJECT_CLASS (g_local_file_parent_class)->finalize) (object);
112 }
113
114 static void
115 g_local_file_class_init (GLocalFileClass *klass)
116 {
117   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
118   GFileAttributeInfoList *list;
119
120   gobject_class->finalize = g_local_file_finalize;
121
122   /* Set up attribute lists */
123
124   /* Writable attributes: */
125
126   list = g_file_attribute_info_list_new ();
127
128   g_file_attribute_info_list_add (list,
129                                   G_FILE_ATTRIBUTE_UNIX_MODE,
130                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
131                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
132   
133 #ifdef HAVE_CHOWN
134   g_file_attribute_info_list_add (list,
135                                   G_FILE_ATTRIBUTE_UNIX_UID,
136                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
137                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
138   g_file_attribute_info_list_add (list,
139                                   G_FILE_ATTRIBUTE_UNIX_GID,
140                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
141                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
142 #endif
143   
144 #ifdef HAVE_SYMLINK
145   g_file_attribute_info_list_add (list,
146                                   G_FILE_ATTRIBUTE_STD_SYMLINK_TARGET,
147                                   G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
148                                   0);
149 #endif
150   
151 #ifdef HAVE_UTIMES
152   g_file_attribute_info_list_add (list,
153                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
154                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
155                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
156   g_file_attribute_info_list_add (list,
157                                   G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
158                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
159                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
160   g_file_attribute_info_list_add (list,
161                                   G_FILE_ATTRIBUTE_TIME_ACCESS,
162                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
163                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
164   g_file_attribute_info_list_add (list,
165                                   G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
166                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
167                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
168 #endif
169
170   local_writable_attributes = list;
171
172   /* Writable namespaces: */
173   
174   list = g_file_attribute_info_list_new ();
175
176 #ifdef HAVE_XATTR
177   g_file_attribute_info_list_add (list,
178                                   "xattr",
179                                   G_FILE_ATTRIBUTE_TYPE_STRING,
180                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WITH_FILE |
181                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
182   g_file_attribute_info_list_add (list,
183                                   "xattr_sys",
184                                   G_FILE_ATTRIBUTE_TYPE_STRING,
185                                   G_FILE_ATTRIBUTE_FLAGS_COPY_WHEN_MOVED);
186 #endif
187
188   local_writable_namespaces = list;
189 }
190
191 static void
192 g_local_file_init (GLocalFile *local)
193 {
194 }
195
196
197 static char *
198 canonicalize_filename (const char *filename)
199 {
200   char *canon, *start, *p, *q;
201   char *cwd;
202   
203   if (!g_path_is_absolute (filename))
204     {
205       cwd = g_get_current_dir ();
206       canon = g_build_filename (cwd, filename, NULL);
207       g_free (cwd);
208     }
209   else
210     canon = g_strdup (filename);
211
212   start = (char *)g_path_skip_root (canon);
213
214   p = start;
215   while (*p != 0)
216     {
217       if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
218         {
219           memmove (p, p+1, strlen (p+1)+1);
220         }
221       else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
222         {
223           q = p + 2;
224           /* Skip previous separator */
225           p = p - 2;
226           if (p < start)
227             p = start;
228           while (p > start && !G_IS_DIR_SEPARATOR (*p))
229             p--;
230           if (G_IS_DIR_SEPARATOR (*p))
231             *p++ = G_DIR_SEPARATOR;
232           memmove (p, q, strlen (q)+1);
233         }
234       else
235         {
236           /* Skip until next separator */
237           while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
238             p++;
239           
240           if (*p != 0)
241             {
242               /* Canonicalize one separator */
243               *p++ = G_DIR_SEPARATOR;
244             }
245         }
246
247       /* Remove additional separators */
248       q = p;
249       while (*q && G_IS_DIR_SEPARATOR (*q))
250         q++;
251
252       if (p != q)
253         memmove (p, q, strlen (q)+1);
254     }
255
256   /* Remove trailing slashes */
257   if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
258     *(p-1) = 0;
259   
260   return canon;
261 }
262
263 /**
264  * _g_local_file_new:
265  * @filename: filename of the file to create.
266  * 
267  * Returns: new local #GFile.
268  **/
269 GFile *
270 _g_local_file_new (const char *filename)
271 {
272   GLocalFile *local;
273
274   local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
275   local->filename = canonicalize_filename (filename);
276   
277   return G_FILE (local);
278 }
279
280 static gboolean
281 g_local_file_is_native (GFile *file)
282 {
283   return TRUE;
284 }
285
286 static gboolean
287 g_local_file_has_uri_scheme (GFile      *file,
288                              const char *uri_scheme)
289 {
290   return g_ascii_strcasecmp (uri_scheme, "file") == 0;
291 }
292
293 static char *
294 g_local_file_get_uri_scheme (GFile *file)
295 {
296   return g_strdup ("file");
297 }
298
299 static char *
300 g_local_file_get_basename (GFile *file)
301 {
302   return g_path_get_basename (G_LOCAL_FILE (file)->filename);
303 }
304
305 static char *
306 g_local_file_get_path (GFile *file)
307 {
308   return g_strdup (G_LOCAL_FILE (file)->filename);
309 }
310
311 static char *
312 g_local_file_get_uri (GFile *file)
313 {
314   return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
315 }
316
317 static gboolean
318 get_filename_charset (const gchar **filename_charset)
319 {
320   const gchar **charsets;
321   gboolean is_utf8;
322   
323   is_utf8 = g_get_filename_charsets (&charsets);
324
325   if (filename_charset)
326     *filename_charset = charsets[0];
327   
328   return is_utf8;
329 }
330
331 static gboolean
332 name_is_valid_for_display (const char *string,
333                            gboolean    is_valid_utf8)
334 {
335   char c;
336   
337   if (!is_valid_utf8 &&
338       !g_utf8_validate (string, -1, NULL))
339     return FALSE;
340
341   while ((c = *string++) != 0)
342     {
343       if (g_ascii_iscntrl(c))
344         return FALSE;
345     }
346
347   return TRUE;
348 }
349
350 static char *
351 g_local_file_get_parse_name (GFile *file)
352 {
353   const char *filename;
354   char *parse_name;
355   const gchar *charset;
356   char *utf8_filename;
357   char *roundtripped_filename;
358   gboolean free_utf8_filename;
359   gboolean is_valid_utf8;
360
361   filename = G_LOCAL_FILE (file)->filename;
362   if (get_filename_charset (&charset))
363     {
364       utf8_filename = (char *)filename;
365       free_utf8_filename = FALSE;
366       is_valid_utf8 = FALSE; /* Can't guarantee this */
367     }
368   else
369     {
370       utf8_filename = g_convert (filename, -1, 
371                                  "UTF-8", charset, NULL, NULL, NULL);
372       free_utf8_filename = TRUE;
373       is_valid_utf8 = TRUE;
374
375       if (utf8_filename != NULL)
376         {
377           /* Make sure we can roundtrip: */
378           roundtripped_filename = g_convert (utf8_filename, -1,
379                                              charset, "UTF-8", NULL, NULL, NULL);
380           
381           if (roundtripped_filename == NULL ||
382               strcmp (utf8_filename, roundtripped_filename) != 0)
383             {
384               g_free (utf8_filename);
385               utf8_filename = NULL;
386             }
387         }
388     }
389
390
391   if (utf8_filename != NULL &&
392       name_is_valid_for_display (utf8_filename, is_valid_utf8))
393     {
394       if (free_utf8_filename)
395         parse_name = utf8_filename;
396       else
397         parse_name = g_strdup (utf8_filename);
398     }
399   else
400     {
401       parse_name = g_filename_to_uri (filename, NULL, NULL);
402       if (free_utf8_filename)
403         g_free (utf8_filename);
404     }
405   
406   return parse_name;
407 }
408
409 static GFile *
410 g_local_file_get_parent (GFile *file)
411 {
412   GLocalFile *local = G_LOCAL_FILE (file);
413   const char *non_root;
414   char *dirname;
415   GFile *parent;
416
417   /* Check for root */
418   non_root = g_path_skip_root (local->filename);
419   if (*non_root == 0)
420     return NULL;
421
422   dirname = g_path_get_dirname (local->filename);
423   parent = _g_local_file_new (dirname);
424   g_free (dirname);
425   return parent;
426 }
427
428 static GFile *
429 g_local_file_dup (GFile *file)
430 {
431   GLocalFile *local = G_LOCAL_FILE (file);
432
433   return _g_local_file_new (local->filename);
434 }
435
436 static guint
437 g_local_file_hash (GFile *file)
438 {
439   GLocalFile *local = G_LOCAL_FILE (file);
440   
441   return g_str_hash (local->filename);
442 }
443
444 static gboolean
445 g_local_file_equal (GFile *file1,
446                     GFile *file2)
447 {
448   GLocalFile *local1 = G_LOCAL_FILE (file1);
449   GLocalFile *local2 = G_LOCAL_FILE (file2);
450
451   return g_str_equal (local1->filename, local2->filename);
452 }
453
454 static const char *
455 match_prefix (const char *path, 
456               const char *prefix)
457 {
458   int prefix_len;
459
460   prefix_len = strlen (prefix);
461   if (strncmp (path, prefix, prefix_len) != 0)
462     return NULL;
463   return path + prefix_len;
464 }
465
466 static gboolean
467 g_local_file_contains_file (GFile *parent,
468                             GFile *descendant)
469 {
470   GLocalFile *parent_local = G_LOCAL_FILE (parent);
471   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
472   const char *remainder;
473
474   remainder = match_prefix (descendant_local->filename, parent_local->filename);
475   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
476     return TRUE;
477   return FALSE;
478 }
479
480 static char *
481 g_local_file_get_relative_path (GFile *parent,
482                                 GFile *descendant)
483 {
484   GLocalFile *parent_local = G_LOCAL_FILE (parent);
485   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
486   const char *remainder;
487
488   remainder = match_prefix (descendant_local->filename, parent_local->filename);
489   
490   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
491     return g_strdup (remainder + 1);
492   return NULL;
493 }
494
495 static GFile *
496 g_local_file_resolve_relative_path (GFile      *file,
497                                     const char *relative_path)
498 {
499   GLocalFile *local = G_LOCAL_FILE (file);
500   char *filename;
501   GFile *child;
502
503   if (g_path_is_absolute (relative_path))
504     return _g_local_file_new (relative_path);
505   
506   filename = g_build_filename (local->filename, relative_path, NULL);
507   child = _g_local_file_new (filename);
508   g_free (filename);
509   
510   return child;
511 }
512
513 static GFileEnumerator *
514 g_local_file_enumerate_children (GFile                *file,
515                                  const char           *attributes,
516                                  GFileQueryInfoFlags   flags,
517                                  GCancellable         *cancellable,
518                                  GError              **error)
519 {
520   GLocalFile *local = G_LOCAL_FILE (file);
521   return _g_local_file_enumerator_new (local->filename,
522                                        attributes, flags,
523                                        cancellable, error);
524 }
525
526 static GFile *
527 g_local_file_get_child_for_display_name (GFile        *file,
528                                          const char   *display_name,
529                                          GError      **error)
530 {
531   GFile *parent, *new_file;
532   char *basename;
533
534   basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
535   if (basename == NULL)
536     {
537       g_set_error (error, G_IO_ERROR,
538                    G_IO_ERROR_INVALID_FILENAME,
539                    _("Invalid filename %s"), display_name);
540       return NULL;
541     }
542
543   parent = g_file_get_parent (file);
544   new_file = g_file_get_child (file, basename);
545   g_object_unref (parent);
546   g_free (basename);
547   
548   return new_file;
549 }
550
551 #ifdef USE_STATFS
552 static const char *
553 get_fs_type (long f_type)
554 {
555
556   /* filesystem ids taken from linux manpage */
557   switch (f_type) 
558     {
559     case 0xadf5:
560       return "adfs";
561     case 0xADFF:
562       return "affs";
563     case 0x42465331:
564       return "befs";
565     case 0x1BADFACE:
566       return "bfs";
567     case 0xFF534D42:
568       return "cifs";
569     case 0x73757245:
570       return "coda";
571     case 0x012FF7B7:
572       return "coh";
573     case 0x28cd3d45:
574       return "cramfs";
575     case 0x1373:
576       return "devfs";
577     case 0x00414A53:
578       return "efs";
579     case 0x137D:
580       return "ext";
581     case 0xEF51:
582       return "ext2";
583     case 0xEF53:
584       return "ext3";
585     case 0x4244:
586       return "hfs";
587     case 0xF995E849:
588       return "hpfs";
589     case 0x958458f6:
590       return "hugetlbfs";
591     case 0x9660:
592       return "isofs";
593     case 0x72b6:
594       return "jffs2";
595     case 0x3153464a:
596       return "jfs";
597     case 0x137F:
598       return "minix";
599     case 0x138F:
600       return "minix2";
601     case 0x2468:
602       return "minix2";
603     case 0x2478:
604       return "minix22";
605     case 0x4d44:
606       return "msdos";
607     case 0x564c:
608       return "ncp";
609     case 0x6969:
610       return "nfs";
611     case 0x5346544e:
612       return "ntfs";
613     case 0x9fa1:
614       return "openprom";
615     case 0x9fa0:
616       return "proc";
617     case 0x002f:
618       return "qnx4";
619     case 0x52654973:
620       return "reiserfs";
621     case 0x7275:
622       return "romfs";
623     case 0x517B:
624       return "smb";
625     case 0x012FF7B6:
626       return "sysv2";
627     case 0x012FF7B5:
628       return "sysv4";
629     case 0x01021994:
630       return "tmpfs";
631     case 0x15013346:
632       return "udf";
633     case 0x00011954:
634       return "ufs";
635     case 0x9fa2:
636       return "usbdevice";
637     case 0xa501FCF5:
638       return "vxfs";
639     case 0x012FF7B4:
640       return "xenix";
641     case 0x58465342:
642       return "xfs";
643     case 0x012FD16D:
644       return "xiafs";
645     default:
646       return NULL;
647     }
648 }
649 #endif
650
651 G_LOCK_DEFINE_STATIC(mount_info_hash);
652 static GHashTable *mount_info_hash = NULL;
653 guint64 mount_info_hash_cache_time = 0;
654
655 typedef enum {
656   MOUNT_INFO_READONLY = 1<<0
657 } MountInfo;
658
659 static gboolean
660 device_equal (gconstpointer v1,
661               gconstpointer v2)
662 {
663   return *(dev_t *)v1 == * (dev_t *)v2;
664 }
665
666 static guint
667 device_hash (gconstpointer v)
668 {
669   return (guint) *(dev_t *)v;
670 }
671
672 static void
673 get_mount_info (GFileInfo             *fs_info,
674                 const char            *path,
675                 GFileAttributeMatcher *matcher)
676 {
677   struct stat buf;
678   gboolean got_info;
679   gpointer info_as_ptr;
680   guint mount_info;
681   char *mountpoint;
682   dev_t *dev;
683   GUnixMount *mount;
684   guint64 cache_time;
685
686   if (lstat (path, &buf) != 0)
687     return;
688
689   G_LOCK (mount_info_hash);
690
691   if (mount_info_hash == NULL)
692     mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
693                                              g_free, NULL);
694
695
696   if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
697     g_hash_table_remove_all (mount_info_hash);
698   
699   got_info = g_hash_table_lookup_extended (mount_info_hash,
700                                            &buf.st_dev,
701                                            NULL,
702                                            &info_as_ptr);
703   
704   G_UNLOCK (mount_info_hash);
705   
706   mount_info = GPOINTER_TO_UINT (info_as_ptr);
707   
708   if (!got_info)
709     {
710       mount_info = 0;
711
712       mountpoint = find_mountpoint_for (path, buf.st_dev);
713       if (mountpoint == NULL)
714         mountpoint = "/";
715
716       mount = g_get_unix_mount_at (mountpoint, &cache_time);
717       if (mount)
718         {
719           if (g_unix_mount_is_readonly (mount))
720             mount_info |= MOUNT_INFO_READONLY;
721           
722           g_unix_mount_free (mount);
723         }
724
725       dev = g_new0 (dev_t, 1);
726       *dev = buf.st_dev;
727       
728       G_LOCK (mount_info_hash);
729       mount_info_hash_cache_time = cache_time;
730       g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
731       G_UNLOCK (mount_info_hash);
732     }
733
734   if (mount_info & MOUNT_INFO_READONLY)
735     g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FS_READONLY, TRUE);
736 }
737
738 static GFileInfo *
739 g_local_file_query_filesystem_info (GFile         *file,
740                                     const char    *attributes,
741                                     GCancellable  *cancellable,
742                                     GError       **error)
743 {
744   GLocalFile *local = G_LOCAL_FILE (file);
745   GFileInfo *info;
746   int statfs_result;
747   gboolean no_size;
748   guint64 block_size;
749 #ifdef USE_STATFS
750   struct statfs statfs_buffer;
751   const char *fstype;
752 #elif defined(USE_STATVFS)
753   struct statvfs statfs_buffer;
754 #endif
755   GFileAttributeMatcher *attribute_matcher;
756         
757   no_size = FALSE;
758   
759 #ifdef USE_STATFS
760   
761 #if STATFS_ARGS == 2
762   statfs_result = statfs (local->filename, &statfs_buffer);
763 #elif STATFS_ARGS == 4
764   statfs_result = statfs (local->filename, &statfs_buffer,
765                           sizeof (statfs_buffer), 0);
766 #endif
767   block_size = statfs_buffer.f_bsize;
768   
769 #if defined(__linux__)
770   /* ncpfs does not know the amount of available and free space *
771    * assuming ncpfs is linux specific, if you are on a non-linux platform
772    * where ncpfs is available, please file a bug about it on bugzilla.gnome.org
773    */
774   if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
775       /* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
776       statfs_buffer.f_type == 0x564c)
777     no_size = TRUE;
778 #endif
779   
780 #elif defined(USE_STATVFS)
781   statfs_result = statvfs (local->filename, &statfs_buffer);
782   block_size = statfs_buffer.f_frsize; 
783 #endif
784
785   if (statfs_result == -1)
786     {
787       g_set_error (error, G_IO_ERROR,
788                    g_io_error_from_errno (errno),
789                    _("Error getting filesystem info: %s"),
790                    g_strerror (errno));
791       return NULL;
792     }
793
794   info = g_file_info_new ();
795
796   attribute_matcher = g_file_attribute_matcher_new (attributes);
797   
798   if (g_file_attribute_matcher_matches (attribute_matcher,
799                                         G_FILE_ATTRIBUTE_FS_FREE))
800     g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FS_FREE, block_size * statfs_buffer.f_bavail);
801   if (g_file_attribute_matcher_matches (attribute_matcher,
802                                         G_FILE_ATTRIBUTE_FS_SIZE))
803     g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FS_SIZE, block_size * statfs_buffer.f_blocks);
804
805 #ifdef USE_STATFS
806   fstype = get_fs_type (statfs_buffer.f_type);
807   if (fstype &&
808       g_file_attribute_matcher_matches (attribute_matcher,
809                                         G_FILE_ATTRIBUTE_FS_TYPE))
810     g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FS_TYPE, fstype);
811 #endif  
812
813   if (g_file_attribute_matcher_matches (attribute_matcher,
814                                         G_FILE_ATTRIBUTE_FS_READONLY))
815     {
816       get_mount_info (info, local->filename, attribute_matcher);
817     }
818   
819   g_file_attribute_matcher_unref (attribute_matcher);
820   
821   return info;
822 }
823
824 static GVolume *
825 g_local_file_find_enclosing_volume (GFile         *file,
826                                     GCancellable  *cancellable,
827                                     GError       **error)
828 {
829   GLocalFile *local = G_LOCAL_FILE (file);
830   struct stat buf;
831   char *mountpoint;
832   GVolume *volume;
833
834   if (lstat (local->filename, &buf) != 0)
835     {
836       g_set_error (error, G_IO_ERROR,
837                    G_IO_ERROR_NOT_FOUND,
838                    _("Containing volume does not exist"));
839       return NULL;
840     }
841
842   mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
843   if (mountpoint == NULL)
844     {
845       g_set_error (error, G_IO_ERROR,
846                    G_IO_ERROR_NOT_FOUND,
847                    _("Containing volume does not exist"));
848       return NULL;
849     }
850
851   volume = _g_volume_get_for_mount_path (mountpoint);
852   g_free (mountpoint);
853   if (volume)
854     return volume;
855
856   g_set_error (error, G_IO_ERROR,
857                G_IO_ERROR_NOT_FOUND,
858                _("Containing volume does not exist"));
859   return NULL;
860 }
861
862 static GFile *
863 g_local_file_set_display_name (GFile         *file,
864                                const char    *display_name,
865                                GCancellable  *cancellable,
866                                GError       **error)
867 {
868   GLocalFile *local, *new_local;
869   GFile *new_file, *parent;
870   struct stat statbuf;
871   int errsv;
872
873   parent = g_file_get_parent (file);
874   if (parent == NULL)
875     {
876       g_set_error (error, G_IO_ERROR,
877                    G_IO_ERROR_FAILED,
878                    _("Can't rename root directory"));
879       return NULL;
880     }
881   
882   new_file = g_file_get_child_for_display_name  (parent, display_name, error);
883   g_object_unref (parent);
884   
885   if (new_file == NULL)
886     return NULL;
887   
888   local = G_LOCAL_FILE (file);
889   new_local = G_LOCAL_FILE (new_file);
890
891   if (!(g_lstat (new_local->filename, &statbuf) == -1 &&
892         errno == ENOENT))
893     {
894       g_set_error (error, G_IO_ERROR,
895                    G_IO_ERROR_EXISTS,
896                    _("Can't rename file, filename already exist"));
897       return NULL;
898     }
899
900   if (rename (local->filename, new_local->filename) == -1)
901     {
902       errsv = errno;
903
904       if (errsv == EINVAL)
905         /* We can't get a rename file into itself error herer,
906            so this must be an invalid filename, on e.g. FAT */
907         g_set_error (error, G_IO_ERROR,
908                      G_IO_ERROR_INVALID_FILENAME,
909                      _("Invalid filename"));
910       else
911         g_set_error (error, G_IO_ERROR,
912                      g_io_error_from_errno (errsv),
913                      _("Error renaming file: %s"),
914                      g_strerror (errsv));
915       g_object_unref (new_file);
916       return NULL;
917     }
918   
919   return new_file;
920 }
921
922 static GFileInfo *
923 g_local_file_query_info (GFile                *file,
924                          const char           *attributes,
925                          GFileQueryInfoFlags   flags,
926                          GCancellable         *cancellable,
927                          GError              **error)
928 {
929   GLocalFile *local = G_LOCAL_FILE (file);
930   GFileInfo *info;
931   GFileAttributeMatcher *matcher;
932   char *basename, *dirname;
933   GLocalParentFileInfo parent_info;
934
935   matcher = g_file_attribute_matcher_new (attributes);
936   
937   basename = g_path_get_basename (local->filename);
938   
939   dirname = g_path_get_dirname (local->filename);
940   _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
941   g_free (dirname);
942   
943   info = _g_local_file_info_get (basename, local->filename,
944                                  matcher, flags, &parent_info,
945                                  error);
946   
947   g_free (basename);
948
949   g_file_attribute_matcher_unref (matcher);
950
951   return info;
952 }
953
954 static GFileAttributeInfoList *
955 g_local_file_query_settable_attributes (GFile         *file,
956                                         GCancellable  *cancellable,
957                                         GError       **error)
958 {
959   return g_file_attribute_info_list_ref (local_writable_attributes);
960 }
961
962 static GFileAttributeInfoList *
963 g_local_file_query_writable_namespaces (GFile         *file,
964                                         GCancellable  *cancellable,
965                                         GError       **error)
966 {
967   return g_file_attribute_info_list_ref (local_writable_namespaces);
968 }
969
970 static gboolean
971 g_local_file_set_attribute (GFile                      *file,
972                             const char                 *attribute,
973                             const GFileAttributeValue  *value,
974                             GFileQueryInfoFlags         flags,
975                             GCancellable               *cancellable,
976                             GError                    **error)
977 {
978   GLocalFile *local = G_LOCAL_FILE (file);
979
980   return _g_local_file_info_set_attribute (local->filename,
981                                            attribute,
982                                            value,
983                                            flags,
984                                            cancellable,
985                                            error);
986 }
987
988 static gboolean
989 g_local_file_set_attributes_from_info (GFile                *file,
990                                        GFileInfo            *info,
991                                        GFileQueryInfoFlags   flags,
992                                        GCancellable         *cancellable,
993                                        GError              **error)
994 {
995   GLocalFile *local = G_LOCAL_FILE (file);
996   int res, chained_res;
997   GFileIface* default_iface;
998
999   res = _g_local_file_info_set_attributes (local->filename,
1000                                            info, flags, 
1001                                            cancellable,
1002                                            error);
1003
1004   if (!res)
1005     error = NULL; /* Don't write over error if further errors */
1006
1007   default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1008
1009   chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1010   
1011   return res && chained_res;
1012 }
1013
1014 static GFileInputStream *
1015 g_local_file_read (GFile         *file,
1016                    GCancellable  *cancellable,
1017                    GError       **error)
1018 {
1019   GLocalFile *local = G_LOCAL_FILE (file);
1020   int fd;
1021   struct stat buf;
1022   
1023   fd = g_open (local->filename, O_RDONLY, 0);
1024   if (fd == -1)
1025     {
1026       g_set_error (error, G_IO_ERROR,
1027                    g_io_error_from_errno (errno),
1028                    _("Error opening file: %s"),
1029                    g_strerror (errno));
1030       return NULL;
1031     }
1032
1033   if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
1034     {
1035       close (fd);
1036       g_set_error (error, G_IO_ERROR,
1037                    G_IO_ERROR_IS_DIRECTORY,
1038                    _("Can't open directory"));
1039       return NULL;
1040     }
1041   
1042   return _g_local_file_input_stream_new (fd);
1043 }
1044
1045 static GFileOutputStream *
1046 g_local_file_append_to (GFile             *file,
1047                         GFileCreateFlags   flags,
1048                         GCancellable      *cancellable,
1049                         GError           **error)
1050 {
1051   return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1052                                              flags, cancellable, error);
1053 }
1054
1055 static GFileOutputStream *
1056 g_local_file_create (GFile             *file,
1057                      GFileCreateFlags   flags,
1058                      GCancellable      *cancellable,
1059                      GError           **error)
1060 {
1061   return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1062                                              flags, cancellable, error);
1063 }
1064
1065 static GFileOutputStream *
1066 g_local_file_replace (GFile             *file,
1067                       const char        *etag,
1068                       gboolean           make_backup,
1069                       GFileCreateFlags   flags,
1070                       GCancellable      *cancellable,
1071                       GError           **error)
1072 {
1073   return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1074                                               etag, make_backup, flags,
1075                                               cancellable, error);
1076 }
1077
1078
1079 static gboolean
1080 g_local_file_delete (GFile         *file,
1081                      GCancellable  *cancellable,
1082                      GError       **error)
1083 {
1084   GLocalFile *local = G_LOCAL_FILE (file);
1085   
1086   if (g_remove (local->filename) == -1)
1087     {
1088       g_set_error (error, G_IO_ERROR,
1089                    g_io_error_from_errno (errno),
1090                    _("Error removing file: %s"),
1091                    g_strerror (errno));
1092       return FALSE;
1093     }
1094   
1095   return TRUE;
1096 }
1097
1098 static char *
1099 strip_trailing_slashes (const char *path)
1100 {
1101   char *path_copy;
1102   int len;
1103
1104   path_copy = g_strdup (path);
1105   len = strlen (path_copy);
1106   while (len > 1 && path_copy[len-1] == '/')
1107     path_copy[--len] = 0;
1108
1109   return path_copy;
1110  }
1111
1112 static char *
1113 expand_symlink (const char *link)
1114 {
1115   char *resolved, *canonical, *parent, *link2;
1116   char symlink_value[4096];
1117   ssize_t res;
1118   
1119   res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1120   if (res == -1)
1121     return g_strdup (link);
1122   symlink_value[res] = 0;
1123   
1124   if (g_path_is_absolute (symlink_value))
1125     return canonicalize_filename (symlink_value);
1126   else
1127     {
1128       link2 = strip_trailing_slashes (link);
1129       parent = g_path_get_dirname (link2);
1130       g_free (link2);
1131       
1132       resolved = g_build_filename (parent, symlink_value, NULL);
1133       g_free (parent);
1134       
1135       canonical = canonicalize_filename (resolved);
1136       
1137       g_free (resolved);
1138
1139       return canonical;
1140     }
1141 }
1142
1143 static char *
1144 get_parent (const char *path, 
1145             dev_t      *parent_dev)
1146 {
1147   char *parent, *tmp;
1148   struct stat parent_stat;
1149   int num_recursions;
1150   char *path_copy;
1151
1152   path_copy = strip_trailing_slashes (path);
1153   
1154   parent = g_path_get_dirname (path_copy);
1155   if (strcmp (parent, ".") == 0 ||
1156       strcmp (parent, path_copy) == 0)
1157     {
1158       g_free (path_copy);
1159       return NULL;
1160     }
1161   g_free (path_copy);
1162
1163   num_recursions = 0;
1164   do {
1165     if (g_lstat (parent, &parent_stat) != 0)
1166       {
1167         g_free (parent);
1168         return NULL;
1169       }
1170     
1171     if (S_ISLNK (parent_stat.st_mode))
1172       {
1173         tmp = parent;
1174         parent = expand_symlink (parent);
1175         g_free (tmp);
1176       }
1177     
1178     num_recursions++;
1179     if (num_recursions > 12)
1180       {
1181         g_free (parent);
1182         return NULL;
1183       }
1184   } while (S_ISLNK (parent_stat.st_mode));
1185
1186   *parent_dev = parent_stat.st_dev;
1187   
1188   return parent;
1189 }
1190
1191 static char *
1192 expand_all_symlinks (const char *path)
1193 {
1194   char *parent, *parent_expanded;
1195   char *basename, *res;
1196   dev_t parent_dev;
1197
1198   parent = get_parent (path, &parent_dev);
1199   if (parent)
1200     {
1201       parent_expanded = expand_all_symlinks (parent);
1202       g_free (parent);
1203       basename = g_path_get_basename (path);
1204       res = g_build_filename (parent_expanded, basename, NULL);
1205       g_free (basename);
1206       g_free (parent_expanded);
1207     }
1208   else
1209     res = g_strdup (path);
1210   
1211   return res;
1212 }
1213
1214 static char *
1215 find_mountpoint_for (const char *file, 
1216                      dev_t       dev)
1217 {
1218   char *dir, *parent;
1219   dev_t dir_dev, parent_dev;
1220
1221   dir = g_strdup (file);
1222   dir_dev = dev;
1223
1224   while (1) 
1225     {
1226       parent = get_parent (dir, &parent_dev);
1227       if (parent == NULL)
1228         return dir;
1229     
1230       if (parent_dev != dir_dev)
1231         {
1232           g_free (parent);
1233           return dir;
1234         }
1235     
1236       g_free (dir);
1237       dir = parent;
1238     }
1239 }
1240
1241 static char *
1242 find_topdir_for (const char *file)
1243 {
1244   char *dir;
1245   dev_t dir_dev;
1246
1247   dir = get_parent (file, &dir_dev);
1248   if (dir == NULL)
1249     return NULL;
1250
1251   return find_mountpoint_for (dir, dir_dev);
1252 }
1253
1254 static char *
1255 get_unique_filename (const char *basename, 
1256                      int         id)
1257 {
1258   const char *dot;
1259       
1260   if (id == 1)
1261     return g_strdup (basename);
1262
1263   dot = strchr (basename, '.');
1264   if (dot)
1265     return g_strdup_printf ("%.*s.%d%s", dot - basename, basename, id, dot);
1266   else
1267     return g_strdup_printf ("%s.%d", basename, id);
1268 }
1269
1270 static gboolean
1271 path_has_prefix (const char *path, 
1272                  const char *prefix)
1273 {
1274   int prefix_len;
1275
1276   if (prefix == NULL)
1277     return TRUE;
1278
1279   prefix_len = strlen (prefix);
1280   
1281   if (strncmp (path, prefix, prefix_len) == 0 &&
1282       (prefix_len == 0 || /* empty prefix always matches */
1283        prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1284        path[prefix_len] == 0 ||
1285        path[prefix_len] == '/'))
1286     return TRUE;
1287   
1288   return FALSE;
1289 }
1290
1291 static char *
1292 try_make_relative (const char *path, 
1293                    const char *base)
1294 {
1295   char *path2, *base2;
1296   char *relative;
1297
1298   path2 = expand_all_symlinks (path);
1299   base2 = expand_all_symlinks (base);
1300
1301   relative = NULL;
1302   if (path_has_prefix (path2, base2))
1303     {
1304       relative = path2 + strlen (base2);
1305       while (*relative == '/')
1306         relative ++;
1307       relative = g_strdup (relative);
1308     }
1309   g_free (path2);
1310   g_free (base2);
1311
1312   if (relative)
1313     return relative;
1314   
1315   /* Failed, use abs path */
1316   return g_strdup (path);
1317 }
1318
1319 static char *
1320 escape_trash_name (char *name)
1321 {
1322   GString *str;
1323   const gchar hex[16] = "0123456789ABCDEF";
1324   
1325   str = g_string_new ("");
1326
1327   while (*name != 0)
1328     {
1329       char c;
1330
1331       c = *name++;
1332
1333       if (g_ascii_isprint (c))
1334         g_string_append_c (str, c);
1335       else
1336         {
1337           g_string_append_c (str, '%');
1338           g_string_append_c (str, hex[((guchar)c) >> 4]);
1339           g_string_append_c (str, hex[((guchar)c) & 0xf]);
1340         }
1341     }
1342
1343   return g_string_free (str, FALSE);
1344 }
1345
1346 static gboolean
1347 g_local_file_trash (GFile         *file,
1348                     GCancellable  *cancellable,
1349                     GError       **error)
1350 {
1351   GLocalFile *local = G_LOCAL_FILE (file);
1352   struct stat file_stat, home_stat, trash_stat, global_stat;
1353   const char *homedir;
1354   char *dirname;
1355   char *trashdir, *globaldir, *topdir, *infodir, *filesdir;
1356   char *basename, *trashname, *trashfile, *infoname, *infofile;
1357   char *original_name, *original_name_escaped;
1358   uid_t uid;
1359   char uid_str[32];
1360   int i;
1361   char *data;
1362   gboolean is_homedir_trash;
1363   time_t t;
1364   struct tm now;
1365   char delete_time[32];
1366   int fd;
1367   
1368   if (g_lstat (local->filename, &file_stat) != 0)
1369     {
1370       g_set_error (error, G_IO_ERROR,
1371                    g_io_error_from_errno (errno),
1372                    _("Error trashing file: %s"),
1373                    g_strerror (errno));
1374       return FALSE;
1375     }
1376     
1377   homedir = g_get_home_dir ();
1378   g_stat (homedir, &home_stat);
1379
1380   is_homedir_trash = FALSE;
1381   trashdir = NULL;
1382   if (file_stat.st_dev == home_stat.st_dev)
1383     {
1384       is_homedir_trash = TRUE;
1385       errno = 0;
1386       trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1387       if (g_mkdir_with_parents (trashdir, 0700) < 0)
1388         {
1389           char *display_name;
1390           int err;
1391
1392           err = errno;
1393           display_name = g_filename_display_name (trashdir);
1394           g_set_error (error, G_IO_ERROR,
1395                        g_io_error_from_errno (err),
1396                        _("Unable to create trash dir %s: %s"),
1397                        display_name, g_strerror (err));
1398           g_free (display_name);
1399           g_free (trashdir);
1400           return FALSE;
1401         }
1402       topdir = g_strdup (g_get_user_data_dir ());
1403     }
1404   else
1405     {
1406       uid = geteuid ();
1407       g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1408       
1409       topdir = find_topdir_for (local->filename);
1410       if (topdir == NULL)
1411         {
1412           g_set_error (error, G_IO_ERROR,
1413                        G_IO_ERROR_NOT_SUPPORTED,
1414                        _("Unable to find toplevel directory for trash"));
1415           return FALSE;
1416         }
1417       
1418       /* Try looking for global trash dir $topdir/.Trash/$uid */
1419       globaldir = g_build_filename (topdir, ".Trash", NULL);
1420       if (g_lstat (globaldir, &global_stat) == 0 &&
1421           S_ISDIR (global_stat.st_mode) &&
1422           (global_stat.st_mode & S_ISVTX) != 0)
1423         {
1424           trashdir = g_build_filename (globaldir, uid_str, NULL);
1425
1426           if (g_lstat (trashdir, &trash_stat) == 0)
1427             {
1428               if (!S_ISDIR (trash_stat.st_mode) ||
1429                   trash_stat.st_uid != uid)
1430                 {
1431                   /* Not a directory or not owned by user, ignore */
1432                   g_free (trashdir);
1433                   trashdir = NULL;
1434                 }
1435             }
1436           else if (g_mkdir (trashdir, 0700) == -1)
1437             {
1438               g_free (trashdir);
1439               trashdir = NULL;
1440             }
1441         }
1442       g_free (globaldir);
1443
1444       if (trashdir == NULL)
1445         {
1446           /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1447           dirname = g_strdup_printf (".Trash-%s", uid_str);
1448           trashdir = g_build_filename (topdir, dirname, NULL);
1449           g_free (dirname);
1450           
1451           if (g_lstat (trashdir, &trash_stat) == 0)
1452             {
1453               if (!S_ISDIR (trash_stat.st_mode) ||
1454                   trash_stat.st_uid != uid)
1455                 {
1456                   /* Not a directory or not owned by user, ignore */
1457                   g_free (trashdir);
1458                   trashdir = NULL;
1459                 }
1460             }
1461           else if (g_mkdir (trashdir, 0700) == -1)
1462             {
1463               g_free (trashdir);
1464               trashdir = NULL;
1465             }
1466         }
1467
1468       if (trashdir == NULL)
1469         {
1470           g_free (topdir);
1471           g_set_error (error, G_IO_ERROR,
1472                        G_IO_ERROR_NOT_SUPPORTED,
1473                        _("Unable to find or create trash directory"));
1474           return FALSE;
1475         }
1476     }
1477
1478   /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1479
1480   infodir = g_build_filename (trashdir, "info", NULL);
1481   filesdir = g_build_filename (trashdir, "files", NULL);
1482   g_free (trashdir);
1483
1484   /* Make sure we have the subdirectories */
1485   if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1486       (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1487     {
1488       g_free (topdir);
1489       g_free (infodir);
1490       g_free (filesdir);
1491       g_set_error (error, G_IO_ERROR,
1492                    G_IO_ERROR_NOT_SUPPORTED,
1493                    _("Unable to find or create trash directory"));
1494       return FALSE;
1495     }  
1496
1497   basename = g_path_get_basename (local->filename);
1498   i = 1;
1499   trashname = NULL;
1500   infofile = NULL;
1501   do {
1502     g_free (trashname);
1503     g_free (infofile);
1504     
1505     trashname = get_unique_filename (basename, i++);
1506     infoname = g_strconcat (trashname, ".trashinfo", NULL);
1507     infofile = g_build_filename (infodir, infoname, NULL);
1508     g_free (infoname);
1509
1510     fd = open (infofile, O_CREAT | O_EXCL, 0666);
1511   } while (fd == -1 && errno == EEXIST);
1512
1513   g_free (basename);
1514   g_free (infodir);
1515
1516   if (fd == -1)
1517     {
1518       g_free (filesdir);
1519       g_free (topdir);
1520       g_free (trashname);
1521       g_free (infofile);
1522       
1523       g_set_error (error, G_IO_ERROR,
1524                    g_io_error_from_errno (errno),
1525                    _("Unable to create trashed file: %s"),
1526                    g_strerror (errno));
1527       return FALSE;
1528     }
1529
1530   close (fd);
1531
1532   /* TODO: Maybe we should verify that you can delete the file from the trash
1533      before moving it? OTOH, that is hard, as it needs a recursive scan */
1534
1535   trashfile = g_build_filename (filesdir, trashname, NULL);
1536
1537   g_free (filesdir);
1538
1539   if (g_rename (local->filename, trashfile) == -1)
1540     {
1541       g_free (topdir);
1542       g_free (trashname);
1543       g_free (infofile);
1544       g_free (trashfile);
1545       
1546       g_set_error (error, G_IO_ERROR,
1547                    g_io_error_from_errno (errno),
1548                    _("Unable to trash file: %s"),
1549                    g_strerror (errno));
1550       return FALSE;
1551     }
1552
1553   g_free (trashfile);
1554
1555   /* TODO: Do we need to update mtime/atime here after the move? */
1556
1557   /* Use absolute names for homedir */
1558   if (is_homedir_trash)
1559     original_name = g_strdup (local->filename);
1560   else
1561     original_name = try_make_relative (local->filename, topdir);
1562   original_name_escaped = escape_trash_name (original_name);
1563   
1564   g_free (original_name);
1565   g_free (topdir);
1566   
1567   t = time (NULL);
1568   localtime_r (&t, &now);
1569   delete_time[0] = 0;
1570   strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
1571
1572   data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
1573                           original_name_escaped, delete_time);
1574
1575   g_file_set_contents (infofile, data, -1, NULL);
1576   g_free (infofile);
1577   g_free (data);
1578   
1579   g_free (original_name_escaped);
1580   g_free (trashname);
1581   
1582   return TRUE;
1583 }
1584
1585 static gboolean
1586 g_local_file_make_directory (GFile         *file,
1587                              GCancellable  *cancellable,
1588                              GError       **error)
1589 {
1590   GLocalFile *local = G_LOCAL_FILE (file);
1591   
1592   if (g_mkdir (local->filename, 0755) == -1)
1593     {
1594       int errsv = errno;
1595
1596       if (errsv == EINVAL)
1597         /* This must be an invalid filename, on e.g. FAT */
1598         g_set_error (error, G_IO_ERROR,
1599                      G_IO_ERROR_INVALID_FILENAME,
1600                      _("Invalid filename"));
1601       else
1602         g_set_error (error, G_IO_ERROR,
1603                      g_io_error_from_errno (errsv),
1604                      _("Error removing file: %s"),
1605                      g_strerror (errsv));
1606       return FALSE;
1607     }
1608   
1609   return TRUE;
1610 }
1611
1612 static gboolean
1613 g_local_file_make_symbolic_link (GFile         *file,
1614                                  const char    *symlink_value,
1615                                  GCancellable  *cancellable,
1616                                  GError       **error)
1617 {
1618 #ifdef HAVE_SYMLINK
1619   GLocalFile *local = G_LOCAL_FILE (file);
1620   
1621   if (symlink (symlink_value, local->filename) == -1)
1622     {
1623       int errsv = errno;
1624
1625       if (errsv == EINVAL)
1626         /* This must be an invalid filename, on e.g. FAT */
1627         g_set_error (error, G_IO_ERROR,
1628                      G_IO_ERROR_INVALID_FILENAME,
1629                      _("Invalid filename"));
1630       else
1631         g_set_error (error, G_IO_ERROR,
1632                      g_io_error_from_errno (errsv),
1633                      _("Error making symbolic link: %s"),
1634                      g_strerror (errsv));
1635       return FALSE;
1636     }
1637   return TRUE;
1638 #else
1639   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
1640   return FALSE;
1641 #endif
1642 }
1643
1644
1645 static gboolean
1646 g_local_file_copy (GFile                  *source,
1647                    GFile                  *destination,
1648                    GFileCopyFlags          flags,
1649                    GCancellable           *cancellable,
1650                    GFileProgressCallback   progress_callback,
1651                    gpointer                progress_callback_data,
1652                    GError                **error)
1653 {
1654   /* Fall back to default copy */
1655   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
1656   return FALSE;
1657 }
1658
1659 static gboolean
1660 g_local_file_move (GFile                  *source,
1661                    GFile                  *destination,
1662                    GFileCopyFlags          flags,
1663                    GCancellable           *cancellable,
1664                    GFileProgressCallback   progress_callback,
1665                    gpointer                progress_callback_data,
1666                    GError                **error)
1667 {
1668   GLocalFile *local_source = G_LOCAL_FILE (source);
1669   GLocalFile *local_destination = G_LOCAL_FILE (destination);
1670   struct stat statbuf;
1671   gboolean destination_exist, source_is_dir;
1672   char *backup_name;
1673   int res;
1674
1675   res = g_lstat (local_source->filename, &statbuf);
1676   if (res == -1)
1677     {
1678       g_set_error (error, G_IO_ERROR,
1679                    g_io_error_from_errno (errno),
1680                    _("Error moving file: %s"),
1681                    g_strerror (errno));
1682       return FALSE;
1683     }
1684   else
1685     source_is_dir = S_ISDIR (statbuf.st_mode);
1686   
1687   destination_exist = FALSE;
1688   res = g_lstat (local_destination->filename, &statbuf);
1689   if (res == 0)
1690     {
1691       destination_exist = TRUE; /* Target file exists */
1692
1693       if (flags & G_FILE_COPY_OVERWRITE)
1694         {
1695           /* Always fail on dirs, even with overwrite */
1696           if (S_ISDIR (statbuf.st_mode))
1697             {
1698               g_set_error (error,
1699                            G_IO_ERROR,
1700                            G_IO_ERROR_WOULD_MERGE,
1701                            _("Can't move directory over directory"));
1702               return FALSE;
1703             }
1704         }
1705       else
1706         {
1707           g_set_error (error,
1708                        G_IO_ERROR,
1709                        G_IO_ERROR_EXISTS,
1710                        _("Target file already exists"));
1711           return FALSE;
1712         }
1713     }
1714   
1715   if (flags & G_FILE_COPY_BACKUP && destination_exist)
1716     {
1717       backup_name = g_strconcat (local_destination->filename, "~", NULL);
1718       if (rename (local_destination->filename, backup_name) == -1)
1719         {
1720           g_set_error (error,
1721                        G_IO_ERROR,
1722                        G_IO_ERROR_CANT_CREATE_BACKUP,
1723                        _("Backup file creation failed"));
1724           g_free (backup_name);
1725           return FALSE;
1726         }
1727       g_free (backup_name);
1728       destination_exist = FALSE; /* It did, but no more */
1729     }
1730
1731   if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
1732     {
1733       /* Source is a dir, destination exists (and is not a dir, because that would have failed
1734          earlier), and we're overwriting. Manually remove the target so we can do the rename. */
1735       res = unlink (local_destination->filename);
1736       if (res == -1)
1737         {
1738           g_set_error (error, G_IO_ERROR,
1739                        g_io_error_from_errno (errno),
1740                        _("Error removing target file: %s"),
1741                        g_strerror (errno));
1742           return FALSE;
1743         }
1744     }
1745   
1746   if (rename (local_source->filename, local_destination->filename) == -1)
1747     {
1748       int errsv = errno;
1749
1750       if (errsv == EXDEV)
1751         /* This will cause the fallback code to run */
1752         g_set_error (error, G_IO_ERROR,
1753                      G_IO_ERROR_NOT_SUPPORTED,
1754                      _("Move between mounts not supported"));
1755       else if (errsv == EINVAL)
1756         /* This must be an invalid filename, on e.g. FAT, or
1757            we're trying to move the file into itself...
1758            We return invalid filename for both... */
1759         g_set_error (error, G_IO_ERROR,
1760                      G_IO_ERROR_INVALID_FILENAME,
1761                      _("Invalid filename"));
1762       else
1763         g_set_error (error, G_IO_ERROR,
1764                      g_io_error_from_errno (errsv),
1765                      _("Error moving file: %s"),
1766                      g_strerror (errsv));
1767       return FALSE;
1768
1769     }
1770   return TRUE;
1771 }
1772
1773 static GDirectoryMonitor*
1774 g_local_file_monitor_dir (GFile             *file,
1775                           GFileMonitorFlags  flags,
1776                           GCancellable      *cancellable)
1777 {
1778   GLocalFile* local_file = G_LOCAL_FILE(file);
1779   return _g_local_directory_monitor_new (local_file->filename, flags);
1780 }
1781
1782 static GFileMonitor*
1783 g_local_file_monitor_file (GFile             *file,
1784                            GFileMonitorFlags  flags,
1785                            GCancellable      *cancellable)
1786 {
1787   GLocalFile* local_file = G_LOCAL_FILE(file);
1788   return _g_local_file_monitor_new (local_file->filename, flags);
1789 }
1790
1791 static void
1792 g_local_file_file_iface_init (GFileIface *iface)
1793 {
1794   iface->dup = g_local_file_dup;
1795   iface->hash = g_local_file_hash;
1796   iface->equal = g_local_file_equal;
1797   iface->is_native = g_local_file_is_native;
1798   iface->has_uri_scheme = g_local_file_has_uri_scheme;
1799   iface->get_uri_scheme = g_local_file_get_uri_scheme;
1800   iface->get_basename = g_local_file_get_basename;
1801   iface->get_path = g_local_file_get_path;
1802   iface->get_uri = g_local_file_get_uri;
1803   iface->get_parse_name = g_local_file_get_parse_name;
1804   iface->get_parent = g_local_file_get_parent;
1805   iface->contains_file = g_local_file_contains_file;
1806   iface->get_relative_path = g_local_file_get_relative_path;
1807   iface->resolve_relative_path = g_local_file_resolve_relative_path;
1808   iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
1809   iface->set_display_name = g_local_file_set_display_name;
1810   iface->enumerate_children = g_local_file_enumerate_children;
1811   iface->query_info = g_local_file_query_info;
1812   iface->query_filesystem_info = g_local_file_query_filesystem_info;
1813   iface->find_enclosing_volume = g_local_file_find_enclosing_volume;
1814   iface->query_settable_attributes = g_local_file_query_settable_attributes;
1815   iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
1816   iface->set_attribute = g_local_file_set_attribute;
1817   iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
1818   iface->read = g_local_file_read;
1819   iface->append_to = g_local_file_append_to;
1820   iface->create = g_local_file_create;
1821   iface->replace = g_local_file_replace;
1822   iface->delete_file = g_local_file_delete;
1823   iface->trash = g_local_file_trash;
1824   iface->make_directory = g_local_file_make_directory;
1825   iface->make_symbolic_link = g_local_file_make_symbolic_link;
1826   iface->copy = g_local_file_copy;
1827   iface->move = g_local_file_move;
1828   iface->monitor_dir = g_local_file_monitor_dir;
1829   iface->monitor_file = g_local_file_monitor_file;
1830 }