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