x86_64 fix
[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   return path + prefix_len;
479 }
480
481 static gboolean
482 g_local_file_contains_file (GFile *parent,
483                             GFile *descendant)
484 {
485   GLocalFile *parent_local = G_LOCAL_FILE (parent);
486   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
487   const char *remainder;
488
489   remainder = match_prefix (descendant_local->filename, parent_local->filename);
490   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
491     return TRUE;
492   return FALSE;
493 }
494
495 static char *
496 g_local_file_get_relative_path (GFile *parent,
497                                 GFile *descendant)
498 {
499   GLocalFile *parent_local = G_LOCAL_FILE (parent);
500   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
501   const char *remainder;
502
503   remainder = match_prefix (descendant_local->filename, parent_local->filename);
504   
505   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
506     return g_strdup (remainder + 1);
507   return NULL;
508 }
509
510 static GFile *
511 g_local_file_resolve_relative_path (GFile      *file,
512                                     const char *relative_path)
513 {
514   GLocalFile *local = G_LOCAL_FILE (file);
515   char *filename;
516   GFile *child;
517
518   if (g_path_is_absolute (relative_path))
519     return _g_local_file_new (relative_path);
520   
521   filename = g_build_filename (local->filename, relative_path, NULL);
522   child = _g_local_file_new (filename);
523   g_free (filename);
524   
525   return child;
526 }
527
528 static GFileEnumerator *
529 g_local_file_enumerate_children (GFile                *file,
530                                  const char           *attributes,
531                                  GFileQueryInfoFlags   flags,
532                                  GCancellable         *cancellable,
533                                  GError              **error)
534 {
535   GLocalFile *local = G_LOCAL_FILE (file);
536   return _g_local_file_enumerator_new (local->filename,
537                                        attributes, flags,
538                                        cancellable, error);
539 }
540
541 static GFile *
542 g_local_file_get_child_for_display_name (GFile        *file,
543                                          const char   *display_name,
544                                          GError      **error)
545 {
546   GFile *parent, *new_file;
547   char *basename;
548
549   basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
550   if (basename == NULL)
551     {
552       g_set_error (error, G_IO_ERROR,
553                    G_IO_ERROR_INVALID_FILENAME,
554                    _("Invalid filename %s"), display_name);
555       return NULL;
556     }
557
558   parent = g_file_get_parent (file);
559   new_file = g_file_get_child (file, basename);
560   g_object_unref (parent);
561   g_free (basename);
562   
563   return new_file;
564 }
565
566 #ifdef USE_STATFS
567 static const char *
568 get_fs_type (long f_type)
569 {
570
571   /* filesystem ids taken from linux manpage */
572   switch (f_type) 
573     {
574     case 0xadf5:
575       return "adfs";
576     case 0xADFF:
577       return "affs";
578     case 0x42465331:
579       return "befs";
580     case 0x1BADFACE:
581       return "bfs";
582     case 0xFF534D42:
583       return "cifs";
584     case 0x73757245:
585       return "coda";
586     case 0x012FF7B7:
587       return "coh";
588     case 0x28cd3d45:
589       return "cramfs";
590     case 0x1373:
591       return "devfs";
592     case 0x00414A53:
593       return "efs";
594     case 0x137D:
595       return "ext";
596     case 0xEF51:
597       return "ext2";
598     case 0xEF53:
599       return "ext3";
600     case 0x4244:
601       return "hfs";
602     case 0xF995E849:
603       return "hpfs";
604     case 0x958458f6:
605       return "hugetlbfs";
606     case 0x9660:
607       return "isofs";
608     case 0x72b6:
609       return "jffs2";
610     case 0x3153464a:
611       return "jfs";
612     case 0x137F:
613       return "minix";
614     case 0x138F:
615       return "minix2";
616     case 0x2468:
617       return "minix2";
618     case 0x2478:
619       return "minix22";
620     case 0x4d44:
621       return "msdos";
622     case 0x564c:
623       return "ncp";
624     case 0x6969:
625       return "nfs";
626     case 0x5346544e:
627       return "ntfs";
628     case 0x9fa1:
629       return "openprom";
630     case 0x9fa0:
631       return "proc";
632     case 0x002f:
633       return "qnx4";
634     case 0x52654973:
635       return "reiserfs";
636     case 0x7275:
637       return "romfs";
638     case 0x517B:
639       return "smb";
640     case 0x012FF7B6:
641       return "sysv2";
642     case 0x012FF7B5:
643       return "sysv4";
644     case 0x01021994:
645       return "tmpfs";
646     case 0x15013346:
647       return "udf";
648     case 0x00011954:
649       return "ufs";
650     case 0x9fa2:
651       return "usbdevice";
652     case 0xa501FCF5:
653       return "vxfs";
654     case 0x012FF7B4:
655       return "xenix";
656     case 0x58465342:
657       return "xfs";
658     case 0x012FD16D:
659       return "xiafs";
660     default:
661       return NULL;
662     }
663 }
664 #endif
665
666 #ifndef G_OS_WIN32
667
668 G_LOCK_DEFINE_STATIC(mount_info_hash);
669 static GHashTable *mount_info_hash = NULL;
670 static guint64 mount_info_hash_cache_time = 0;
671
672 typedef enum {
673   MOUNT_INFO_READONLY = 1<<0
674 } MountInfo;
675
676 static gboolean
677 device_equal (gconstpointer v1,
678               gconstpointer v2)
679 {
680   return *(dev_t *)v1 == * (dev_t *)v2;
681 }
682
683 static guint
684 device_hash (gconstpointer v)
685 {
686   return (guint) *(dev_t *)v;
687 }
688
689 static void
690 get_mount_info (GFileInfo             *fs_info,
691                 const char            *path,
692                 GFileAttributeMatcher *matcher)
693 {
694   struct stat buf;
695   gboolean got_info;
696   gpointer info_as_ptr;
697   guint mount_info;
698   char *mountpoint;
699   dev_t *dev;
700   GUnixMountEntry *mount;
701   guint64 cache_time;
702
703   if (g_lstat (path, &buf) != 0)
704     return;
705
706   G_LOCK (mount_info_hash);
707
708   if (mount_info_hash == NULL)
709     mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
710                                              g_free, NULL);
711
712
713   if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
714     g_hash_table_remove_all (mount_info_hash);
715   
716   got_info = g_hash_table_lookup_extended (mount_info_hash,
717                                            &buf.st_dev,
718                                            NULL,
719                                            &info_as_ptr);
720   
721   G_UNLOCK (mount_info_hash);
722   
723   mount_info = GPOINTER_TO_UINT (info_as_ptr);
724   
725   if (!got_info)
726     {
727       mount_info = 0;
728
729       mountpoint = find_mountpoint_for (path, buf.st_dev);
730       if (mountpoint == NULL)
731         mountpoint = "/";
732
733       mount = g_unix_mount_at (mountpoint, &cache_time);
734       if (mount)
735         {
736           if (g_unix_mount_is_readonly (mount))
737             mount_info |= MOUNT_INFO_READONLY;
738           
739           g_unix_mount_free (mount);
740         }
741
742       dev = g_new0 (dev_t, 1);
743       *dev = buf.st_dev;
744       
745       G_LOCK (mount_info_hash);
746       mount_info_hash_cache_time = cache_time;
747       g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
748       G_UNLOCK (mount_info_hash);
749     }
750
751   if (mount_info & MOUNT_INFO_READONLY)
752     g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
753 }
754
755 #endif
756
757 static GFileInfo *
758 g_local_file_query_filesystem_info (GFile         *file,
759                                     const char    *attributes,
760                                     GCancellable  *cancellable,
761                                     GError       **error)
762 {
763   GLocalFile *local = G_LOCAL_FILE (file);
764   GFileInfo *info;
765   int statfs_result;
766   gboolean no_size;
767 #ifndef G_OS_WIN32
768   guint64 block_size;
769 #ifdef USE_STATFS
770   struct statfs statfs_buffer;
771   const char *fstype;
772 #elif defined(USE_STATVFS)
773   struct statvfs statfs_buffer;
774 #endif
775 #endif
776   GFileAttributeMatcher *attribute_matcher;
777         
778   no_size = FALSE;
779   
780 #ifdef USE_STATFS
781   
782 #if STATFS_ARGS == 2
783   statfs_result = statfs (local->filename, &statfs_buffer);
784 #elif STATFS_ARGS == 4
785   statfs_result = statfs (local->filename, &statfs_buffer,
786                           sizeof (statfs_buffer), 0);
787 #endif
788   block_size = statfs_buffer.f_bsize;
789   
790 #if defined(__linux__)
791   /* ncpfs does not know the amount of available and free space *
792    * assuming ncpfs is linux specific, if you are on a non-linux platform
793    * where ncpfs is available, please file a bug about it on bugzilla.gnome.org
794    */
795   if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
796       /* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
797       statfs_buffer.f_type == 0x564c)
798     no_size = TRUE;
799 #endif
800   
801 #elif defined(USE_STATVFS)
802   statfs_result = statvfs (local->filename, &statfs_buffer);
803   block_size = statfs_buffer.f_frsize; 
804 #endif
805
806   if (statfs_result == -1)
807     {
808       g_set_error (error, G_IO_ERROR,
809                    g_io_error_from_errno (errno),
810                    _("Error getting filesystem info: %s"),
811                    g_strerror (errno));
812       return NULL;
813     }
814
815   info = g_file_info_new ();
816
817   attribute_matcher = g_file_attribute_matcher_new (attributes);
818   
819   if (g_file_attribute_matcher_matches (attribute_matcher,
820                                         G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
821     {
822 #ifdef G_OS_WIN32
823       gchar *localdir = g_path_get_dirname (local->filename);
824       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
825       ULARGE_INTEGER li;
826       
827       g_free (localdir);
828       if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
829         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
830       g_free (wdirname);
831 #else
832       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
833 #endif
834     }
835   if (g_file_attribute_matcher_matches (attribute_matcher,
836                                         G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
837     {
838 #ifdef G_OS_WIN32
839       gchar *localdir = g_path_get_dirname (local->filename);
840       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
841       ULARGE_INTEGER li;
842       
843       g_free (localdir);
844       if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
845         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,  (guint64)li.QuadPart);
846       g_free (wdirname);
847 #else
848       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
849 #endif
850     }
851 #ifdef USE_STATFS
852   fstype = get_fs_type (statfs_buffer.f_type);
853   if (fstype &&
854       g_file_attribute_matcher_matches (attribute_matcher,
855                                         G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
856     g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
857 #endif  
858
859   if (g_file_attribute_matcher_matches (attribute_matcher,
860                                         G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
861     {
862 #ifdef G_OS_WIN32
863       /* need to implement with *unix_mount* */
864 #else
865       get_mount_info (info, local->filename, attribute_matcher);
866 #endif
867     }
868   
869   g_file_attribute_matcher_unref (attribute_matcher);
870   
871   return info;
872 }
873
874 static GMount *
875 g_local_file_find_enclosing_mount (GFile         *file,
876                                    GCancellable  *cancellable,
877                                    GError       **error)
878 {
879   GLocalFile *local = G_LOCAL_FILE (file);
880   struct stat buf;
881   char *mountpoint;
882   GMount *mount;
883
884   if (g_lstat (local->filename, &buf) != 0)
885     {
886       g_set_error (error, G_IO_ERROR,
887                    G_IO_ERROR_NOT_FOUND,
888                    _("Containing mount does not exist"));
889       return NULL;
890     }
891
892   mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
893   if (mountpoint == NULL)
894     {
895       g_set_error (error, G_IO_ERROR,
896                    G_IO_ERROR_NOT_FOUND,
897                    _("Containing mount does not exist"));
898       return NULL;
899     }
900
901   mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
902   g_free (mountpoint);
903   if (mount)
904     return mount;
905
906   g_set_error (error, G_IO_ERROR,
907                G_IO_ERROR_NOT_FOUND,
908                _("Containing mount does not exist"));
909   return NULL;
910 }
911
912 static GFile *
913 g_local_file_set_display_name (GFile         *file,
914                                const char    *display_name,
915                                GCancellable  *cancellable,
916                                GError       **error)
917 {
918   GLocalFile *local, *new_local;
919   GFile *new_file, *parent;
920   struct stat statbuf;
921   int errsv;
922
923   parent = g_file_get_parent (file);
924   if (parent == NULL)
925     {
926       g_set_error (error, G_IO_ERROR,
927                    G_IO_ERROR_FAILED,
928                    _("Can't rename root directory"));
929       return NULL;
930     }
931   
932   new_file = g_file_get_child_for_display_name  (parent, display_name, error);
933   g_object_unref (parent);
934   
935   if (new_file == NULL)
936     return NULL;
937   
938   local = G_LOCAL_FILE (file);
939   new_local = G_LOCAL_FILE (new_file);
940
941   if (!(g_lstat (new_local->filename, &statbuf) == -1 &&
942         errno == ENOENT))
943     {
944       g_set_error (error, G_IO_ERROR,
945                    G_IO_ERROR_EXISTS,
946                    _("Can't rename file, filename already exist"));
947       return NULL;
948     }
949
950   if (rename (local->filename, new_local->filename) == -1)
951     {
952       errsv = errno;
953
954       if (errsv == EINVAL)
955         /* We can't get a rename file into itself error herer,
956            so this must be an invalid filename, on e.g. FAT */
957         g_set_error (error, G_IO_ERROR,
958                      G_IO_ERROR_INVALID_FILENAME,
959                      _("Invalid filename"));
960       else
961         g_set_error (error, G_IO_ERROR,
962                      g_io_error_from_errno (errsv),
963                      _("Error renaming file: %s"),
964                      g_strerror (errsv));
965       g_object_unref (new_file);
966       return NULL;
967     }
968   
969   return new_file;
970 }
971
972 static GFileInfo *
973 g_local_file_query_info (GFile                *file,
974                          const char           *attributes,
975                          GFileQueryInfoFlags   flags,
976                          GCancellable         *cancellable,
977                          GError              **error)
978 {
979   GLocalFile *local = G_LOCAL_FILE (file);
980   GFileInfo *info;
981   GFileAttributeMatcher *matcher;
982   char *basename, *dirname;
983   GLocalParentFileInfo parent_info;
984
985   matcher = g_file_attribute_matcher_new (attributes);
986   
987   basename = g_path_get_basename (local->filename);
988   
989   dirname = g_path_get_dirname (local->filename);
990   _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
991   g_free (dirname);
992   
993   info = _g_local_file_info_get (basename, local->filename,
994                                  matcher, flags, &parent_info,
995                                  error);
996   
997   g_free (basename);
998
999   g_file_attribute_matcher_unref (matcher);
1000
1001   return info;
1002 }
1003
1004 static GFileAttributeInfoList *
1005 g_local_file_query_settable_attributes (GFile         *file,
1006                                         GCancellable  *cancellable,
1007                                         GError       **error)
1008 {
1009   return g_file_attribute_info_list_ref (local_writable_attributes);
1010 }
1011
1012 static GFileAttributeInfoList *
1013 g_local_file_query_writable_namespaces (GFile         *file,
1014                                         GCancellable  *cancellable,
1015                                         GError       **error)
1016 {
1017   return g_file_attribute_info_list_ref (local_writable_namespaces);
1018 }
1019
1020 static gboolean
1021 g_local_file_set_attribute (GFile                      *file,
1022                             const char                 *attribute,
1023                             GFileAttributeType          type,
1024                             gpointer                    value_p,
1025                             GFileQueryInfoFlags         flags,
1026                             GCancellable               *cancellable,
1027                             GError                    **error)
1028 {
1029   GLocalFile *local = G_LOCAL_FILE (file);
1030
1031   return _g_local_file_info_set_attribute (local->filename,
1032                                            attribute,
1033                                            type,
1034                                            value_p,
1035                                            flags,
1036                                            cancellable,
1037                                            error);
1038 }
1039
1040 static gboolean
1041 g_local_file_set_attributes_from_info (GFile                *file,
1042                                        GFileInfo            *info,
1043                                        GFileQueryInfoFlags   flags,
1044                                        GCancellable         *cancellable,
1045                                        GError              **error)
1046 {
1047   GLocalFile *local = G_LOCAL_FILE (file);
1048   int res, chained_res;
1049   GFileIface* default_iface;
1050
1051   res = _g_local_file_info_set_attributes (local->filename,
1052                                            info, flags, 
1053                                            cancellable,
1054                                            error);
1055
1056   if (!res)
1057     error = NULL; /* Don't write over error if further errors */
1058
1059   default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1060
1061   chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1062   
1063   return res && chained_res;
1064 }
1065
1066 static GFileInputStream *
1067 g_local_file_read (GFile         *file,
1068                    GCancellable  *cancellable,
1069                    GError       **error)
1070 {
1071   GLocalFile *local = G_LOCAL_FILE (file);
1072   int fd;
1073   struct stat buf;
1074   
1075   fd = g_open (local->filename, O_RDONLY, 0);
1076   if (fd == -1)
1077     {
1078       g_set_error (error, G_IO_ERROR,
1079                    g_io_error_from_errno (errno),
1080                    _("Error opening file: %s"),
1081                    g_strerror (errno));
1082       return NULL;
1083     }
1084
1085   if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
1086     {
1087       close (fd);
1088       g_set_error (error, G_IO_ERROR,
1089                    G_IO_ERROR_IS_DIRECTORY,
1090                    _("Can't open directory"));
1091       return NULL;
1092     }
1093   
1094   return _g_local_file_input_stream_new (fd);
1095 }
1096
1097 static GFileOutputStream *
1098 g_local_file_append_to (GFile             *file,
1099                         GFileCreateFlags   flags,
1100                         GCancellable      *cancellable,
1101                         GError           **error)
1102 {
1103   return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1104                                              flags, cancellable, error);
1105 }
1106
1107 static GFileOutputStream *
1108 g_local_file_create (GFile             *file,
1109                      GFileCreateFlags   flags,
1110                      GCancellable      *cancellable,
1111                      GError           **error)
1112 {
1113   return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1114                                              flags, cancellable, error);
1115 }
1116
1117 static GFileOutputStream *
1118 g_local_file_replace (GFile             *file,
1119                       const char        *etag,
1120                       gboolean           make_backup,
1121                       GFileCreateFlags   flags,
1122                       GCancellable      *cancellable,
1123                       GError           **error)
1124 {
1125   return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1126                                               etag, make_backup, flags,
1127                                               cancellable, error);
1128 }
1129
1130
1131 static gboolean
1132 g_local_file_delete (GFile         *file,
1133                      GCancellable  *cancellable,
1134                      GError       **error)
1135 {
1136   GLocalFile *local = G_LOCAL_FILE (file);
1137   
1138   if (g_remove (local->filename) == -1)
1139     {
1140       g_set_error (error, G_IO_ERROR,
1141                    g_io_error_from_errno (errno),
1142                    _("Error removing file: %s"),
1143                    g_strerror (errno));
1144       return FALSE;
1145     }
1146   
1147   return TRUE;
1148 }
1149
1150 static char *
1151 strip_trailing_slashes (const char *path)
1152 {
1153   char *path_copy;
1154   int len;
1155
1156   path_copy = g_strdup (path);
1157   len = strlen (path_copy);
1158   while (len > 1 && path_copy[len-1] == '/')
1159     path_copy[--len] = 0;
1160
1161   return path_copy;
1162  }
1163
1164 static char *
1165 expand_symlink (const char *link)
1166 {
1167   char *resolved, *canonical, *parent, *link2;
1168   char symlink_value[4096];
1169 #ifdef G_OS_WIN32
1170 #else
1171   ssize_t res;
1172 #endif
1173   
1174 #ifdef G_OS_WIN32
1175 #else
1176   res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1177   
1178   if (res == -1)
1179     return g_strdup (link);
1180   symlink_value[res] = 0;
1181 #endif
1182   
1183   if (g_path_is_absolute (symlink_value))
1184     return canonicalize_filename (symlink_value);
1185   else
1186     {
1187       link2 = strip_trailing_slashes (link);
1188       parent = g_path_get_dirname (link2);
1189       g_free (link2);
1190       
1191       resolved = g_build_filename (parent, symlink_value, NULL);
1192       g_free (parent);
1193       
1194       canonical = canonicalize_filename (resolved);
1195       
1196       g_free (resolved);
1197
1198       return canonical;
1199     }
1200 }
1201
1202 static char *
1203 get_parent (const char *path, 
1204             dev_t      *parent_dev)
1205 {
1206   char *parent, *tmp;
1207   struct stat parent_stat;
1208   int num_recursions;
1209   char *path_copy;
1210
1211   path_copy = strip_trailing_slashes (path);
1212   
1213   parent = g_path_get_dirname (path_copy);
1214   if (strcmp (parent, ".") == 0 ||
1215       strcmp (parent, path_copy) == 0)
1216     {
1217       g_free (path_copy);
1218       return NULL;
1219     }
1220   g_free (path_copy);
1221
1222   num_recursions = 0;
1223   do {
1224     if (g_lstat (parent, &parent_stat) != 0)
1225       {
1226         g_free (parent);
1227         return NULL;
1228       }
1229     
1230     if (S_ISLNK (parent_stat.st_mode))
1231       {
1232         tmp = parent;
1233         parent = expand_symlink (parent);
1234         g_free (tmp);
1235       }
1236     
1237     num_recursions++;
1238     if (num_recursions > 12)
1239       {
1240         g_free (parent);
1241         return NULL;
1242       }
1243   } while (S_ISLNK (parent_stat.st_mode));
1244
1245   *parent_dev = parent_stat.st_dev;
1246   
1247   return parent;
1248 }
1249
1250 static char *
1251 expand_all_symlinks (const char *path)
1252 {
1253   char *parent, *parent_expanded;
1254   char *basename, *res;
1255   dev_t parent_dev;
1256
1257   parent = get_parent (path, &parent_dev);
1258   if (parent)
1259     {
1260       parent_expanded = expand_all_symlinks (parent);
1261       g_free (parent);
1262       basename = g_path_get_basename (path);
1263       res = g_build_filename (parent_expanded, basename, NULL);
1264       g_free (basename);
1265       g_free (parent_expanded);
1266     }
1267   else
1268     res = g_strdup (path);
1269   
1270   return res;
1271 }
1272
1273 static char *
1274 find_mountpoint_for (const char *file, 
1275                      dev_t       dev)
1276 {
1277   char *dir, *parent;
1278   dev_t dir_dev, parent_dev;
1279
1280   dir = g_strdup (file);
1281   dir_dev = dev;
1282
1283   while (1) 
1284     {
1285       parent = get_parent (dir, &parent_dev);
1286       if (parent == NULL)
1287         return dir;
1288     
1289       if (parent_dev != dir_dev)
1290         {
1291           g_free (parent);
1292           return dir;
1293         }
1294     
1295       g_free (dir);
1296       dir = parent;
1297     }
1298 }
1299
1300 #ifndef G_OS_WIN32
1301
1302 static char *
1303 find_topdir_for (const char *file)
1304 {
1305   char *dir;
1306   dev_t dir_dev;
1307
1308   dir = get_parent (file, &dir_dev);
1309   if (dir == NULL)
1310     return NULL;
1311
1312   return find_mountpoint_for (dir, dir_dev);
1313 }
1314
1315 #endif
1316
1317 static char *
1318 get_unique_filename (const char *basename, 
1319                      int         id)
1320 {
1321   const char *dot;
1322       
1323   if (id == 1)
1324     return g_strdup (basename);
1325
1326   dot = strchr (basename, '.');
1327   if (dot)
1328     return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1329   else
1330     return g_strdup_printf ("%s.%d", basename, id);
1331 }
1332
1333 static gboolean
1334 path_has_prefix (const char *path, 
1335                  const char *prefix)
1336 {
1337   int prefix_len;
1338
1339   if (prefix == NULL)
1340     return TRUE;
1341
1342   prefix_len = strlen (prefix);
1343   
1344   if (strncmp (path, prefix, prefix_len) == 0 &&
1345       (prefix_len == 0 || /* empty prefix always matches */
1346        prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1347        path[prefix_len] == 0 ||
1348        path[prefix_len] == '/'))
1349     return TRUE;
1350   
1351   return FALSE;
1352 }
1353
1354 static char *
1355 try_make_relative (const char *path, 
1356                    const char *base)
1357 {
1358   char *path2, *base2;
1359   char *relative;
1360
1361   path2 = expand_all_symlinks (path);
1362   base2 = expand_all_symlinks (base);
1363
1364   relative = NULL;
1365   if (path_has_prefix (path2, base2))
1366     {
1367       relative = path2 + strlen (base2);
1368       while (*relative == '/')
1369         relative ++;
1370       relative = g_strdup (relative);
1371     }
1372   g_free (path2);
1373   g_free (base2);
1374
1375   if (relative)
1376     return relative;
1377   
1378   /* Failed, use abs path */
1379   return g_strdup (path);
1380 }
1381
1382 static char *
1383 escape_trash_name (char *name)
1384 {
1385   GString *str;
1386   const gchar hex[16] = "0123456789ABCDEF";
1387   
1388   str = g_string_new ("");
1389
1390   while (*name != 0)
1391     {
1392       char c;
1393
1394       c = *name++;
1395
1396       if (g_ascii_isprint (c))
1397         g_string_append_c (str, c);
1398       else
1399         {
1400           g_string_append_c (str, '%');
1401           g_string_append_c (str, hex[((guchar)c) >> 4]);
1402           g_string_append_c (str, hex[((guchar)c) & 0xf]);
1403         }
1404     }
1405
1406   return g_string_free (str, FALSE);
1407 }
1408
1409 static gboolean
1410 g_local_file_trash (GFile         *file,
1411                     GCancellable  *cancellable,
1412                     GError       **error)
1413 {
1414   GLocalFile *local = G_LOCAL_FILE (file);
1415   struct stat file_stat, home_stat;
1416   const char *homedir;
1417   char *trashdir, *topdir, *infodir, *filesdir;
1418   char *basename, *trashname, *trashfile, *infoname, *infofile;
1419   char *original_name, *original_name_escaped;
1420   int i;
1421   char *data;
1422   gboolean is_homedir_trash;
1423   char delete_time[32];
1424   int fd;
1425 #ifndef G_OS_WIN32
1426   struct stat trash_stat, global_stat;
1427   char *dirname, *globaldir;
1428 #endif
1429   
1430   if (g_lstat (local->filename, &file_stat) != 0)
1431     {
1432       g_set_error (error, G_IO_ERROR,
1433                    g_io_error_from_errno (errno),
1434                    _("Error trashing file: %s"),
1435                    g_strerror (errno));
1436       return FALSE;
1437     }
1438     
1439   homedir = g_get_home_dir ();
1440   g_stat (homedir, &home_stat);
1441
1442   is_homedir_trash = FALSE;
1443   trashdir = NULL;
1444   if (file_stat.st_dev == home_stat.st_dev)
1445     {
1446       is_homedir_trash = TRUE;
1447       errno = 0;
1448       trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1449       if (g_mkdir_with_parents (trashdir, 0700) < 0)
1450         {
1451           char *display_name;
1452           int err;
1453
1454           err = errno;
1455           display_name = g_filename_display_name (trashdir);
1456           g_set_error (error, G_IO_ERROR,
1457                        g_io_error_from_errno (err),
1458                        _("Unable to create trash dir %s: %s"),
1459                        display_name, g_strerror (err));
1460           g_free (display_name);
1461           g_free (trashdir);
1462           return FALSE;
1463         }
1464       topdir = g_strdup (g_get_user_data_dir ());
1465     }
1466   else
1467     {
1468 #ifdef G_OS_WIN32
1469       g_warning ("Recycle bin not implemented");
1470 #else
1471       uid_t uid;
1472       char uid_str[32];
1473
1474       uid = geteuid ();
1475       g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1476       
1477       topdir = find_topdir_for (local->filename);
1478       if (topdir == NULL)
1479         {
1480           g_set_error (error, G_IO_ERROR,
1481                        G_IO_ERROR_NOT_SUPPORTED,
1482                        _("Unable to find toplevel directory for trash"));
1483           return FALSE;
1484         }
1485       
1486       /* Try looking for global trash dir $topdir/.Trash/$uid */
1487       globaldir = g_build_filename (topdir, ".Trash", NULL);
1488       if (g_lstat (globaldir, &global_stat) == 0 &&
1489           S_ISDIR (global_stat.st_mode) &&
1490           (global_stat.st_mode & S_ISVTX) != 0)
1491         {
1492           trashdir = g_build_filename (globaldir, uid_str, NULL);
1493
1494           if (g_lstat (trashdir, &trash_stat) == 0)
1495             {
1496               if (!S_ISDIR (trash_stat.st_mode) ||
1497                   trash_stat.st_uid != uid)
1498                 {
1499                   /* Not a directory or not owned by user, ignore */
1500                   g_free (trashdir);
1501                   trashdir = NULL;
1502                 }
1503             }
1504           else if (g_mkdir (trashdir, 0700) == -1)
1505             {
1506               g_free (trashdir);
1507               trashdir = NULL;
1508             }
1509         }
1510       g_free (globaldir);
1511
1512       if (trashdir == NULL)
1513         {
1514           /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1515           dirname = g_strdup_printf (".Trash-%s", uid_str);
1516           trashdir = g_build_filename (topdir, dirname, NULL);
1517           g_free (dirname);
1518           
1519           if (g_lstat (trashdir, &trash_stat) == 0)
1520             {
1521               if (!S_ISDIR (trash_stat.st_mode) ||
1522                   trash_stat.st_uid != uid)
1523                 {
1524                   /* Not a directory or not owned by user, ignore */
1525                   g_free (trashdir);
1526                   trashdir = NULL;
1527                 }
1528             }
1529           else if (g_mkdir (trashdir, 0700) == -1)
1530             {
1531               g_free (trashdir);
1532               trashdir = NULL;
1533             }
1534         }
1535 #endif
1536
1537       if (trashdir == NULL)
1538         {
1539           g_free (topdir);
1540           g_set_error (error, G_IO_ERROR,
1541                        G_IO_ERROR_NOT_SUPPORTED,
1542                        _("Unable to find or create trash directory"));
1543           return FALSE;
1544         }
1545     }
1546
1547   /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1548
1549   infodir = g_build_filename (trashdir, "info", NULL);
1550   filesdir = g_build_filename (trashdir, "files", NULL);
1551   g_free (trashdir);
1552
1553   /* Make sure we have the subdirectories */
1554   if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1555       (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1556     {
1557       g_free (topdir);
1558       g_free (infodir);
1559       g_free (filesdir);
1560       g_set_error (error, G_IO_ERROR,
1561                    G_IO_ERROR_NOT_SUPPORTED,
1562                    _("Unable to find or create trash directory"));
1563       return FALSE;
1564     }  
1565
1566   basename = g_path_get_basename (local->filename);
1567   i = 1;
1568   trashname = NULL;
1569   infofile = NULL;
1570   do {
1571     g_free (trashname);
1572     g_free (infofile);
1573     
1574     trashname = get_unique_filename (basename, i++);
1575     infoname = g_strconcat (trashname, ".trashinfo", NULL);
1576     infofile = g_build_filename (infodir, infoname, NULL);
1577     g_free (infoname);
1578
1579     fd = open (infofile, O_CREAT | O_EXCL, 0666);
1580   } while (fd == -1 && errno == EEXIST);
1581
1582   g_free (basename);
1583   g_free (infodir);
1584
1585   if (fd == -1)
1586     {
1587       g_free (filesdir);
1588       g_free (topdir);
1589       g_free (trashname);
1590       g_free (infofile);
1591       
1592       g_set_error (error, G_IO_ERROR,
1593                    g_io_error_from_errno (errno),
1594                    _("Unable to create trashed file: %s"),
1595                    g_strerror (errno));
1596       return FALSE;
1597     }
1598
1599   close (fd);
1600
1601   /* TODO: Maybe we should verify that you can delete the file from the trash
1602      before moving it? OTOH, that is hard, as it needs a recursive scan */
1603
1604   trashfile = g_build_filename (filesdir, trashname, NULL);
1605
1606   g_free (filesdir);
1607
1608   if (g_rename (local->filename, trashfile) == -1)
1609     {
1610       g_free (topdir);
1611       g_free (trashname);
1612       g_free (infofile);
1613       g_free (trashfile);
1614       
1615       g_set_error (error, G_IO_ERROR,
1616                    g_io_error_from_errno (errno),
1617                    _("Unable to trash file: %s"),
1618                    g_strerror (errno));
1619       return FALSE;
1620     }
1621
1622   g_free (trashfile);
1623
1624   /* TODO: Do we need to update mtime/atime here after the move? */
1625
1626   /* Use absolute names for homedir */
1627   if (is_homedir_trash)
1628     original_name = g_strdup (local->filename);
1629   else
1630     original_name = try_make_relative (local->filename, topdir);
1631   original_name_escaped = escape_trash_name (original_name);
1632   
1633   g_free (original_name);
1634   g_free (topdir);
1635   
1636 #ifdef G_OS_WIN32
1637   {
1638     GTimeVal now;
1639     g_get_current_time (&now);
1640     strncpy (delete_time, g_time_val_to_iso8601 (&now), sizeof (delete_time));
1641   }
1642 #else
1643   {
1644     time_t t;
1645     struct tm now;
1646     t = time (NULL);
1647     localtime_r (&t, &now);
1648     delete_time[0] = 0;
1649     strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
1650   }
1651 #endif
1652
1653   data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
1654                           original_name_escaped, delete_time);
1655
1656   g_file_set_contents (infofile, data, -1, NULL);
1657   g_free (infofile);
1658   g_free (data);
1659   
1660   g_free (original_name_escaped);
1661   g_free (trashname);
1662   
1663   return TRUE;
1664 }
1665
1666 static gboolean
1667 g_local_file_make_directory (GFile         *file,
1668                              GCancellable  *cancellable,
1669                              GError       **error)
1670 {
1671   GLocalFile *local = G_LOCAL_FILE (file);
1672   
1673   if (g_mkdir (local->filename, 0755) == -1)
1674     {
1675       int errsv = errno;
1676
1677       if (errsv == EINVAL)
1678         /* This must be an invalid filename, on e.g. FAT */
1679         g_set_error (error, G_IO_ERROR,
1680                      G_IO_ERROR_INVALID_FILENAME,
1681                      _("Invalid filename"));
1682       else
1683         g_set_error (error, G_IO_ERROR,
1684                      g_io_error_from_errno (errsv),
1685                      _("Error removing file: %s"),
1686                      g_strerror (errsv));
1687       return FALSE;
1688     }
1689   
1690   return TRUE;
1691 }
1692
1693 static gboolean
1694 g_local_file_make_symbolic_link (GFile         *file,
1695                                  const char    *symlink_value,
1696                                  GCancellable  *cancellable,
1697                                  GError       **error)
1698 {
1699 #ifdef HAVE_SYMLINK
1700   GLocalFile *local = G_LOCAL_FILE (file);
1701   
1702   if (symlink (symlink_value, local->filename) == -1)
1703     {
1704       int errsv = errno;
1705
1706       if (errsv == EINVAL)
1707         /* This must be an invalid filename, on e.g. FAT */
1708         g_set_error (error, G_IO_ERROR,
1709                      G_IO_ERROR_INVALID_FILENAME,
1710                      _("Invalid filename"));
1711       else
1712         g_set_error (error, G_IO_ERROR,
1713                      g_io_error_from_errno (errsv),
1714                      _("Error making symbolic link: %s"),
1715                      g_strerror (errsv));
1716       return FALSE;
1717     }
1718   return TRUE;
1719 #else
1720   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
1721   return FALSE;
1722 #endif
1723 }
1724
1725
1726 static gboolean
1727 g_local_file_copy (GFile                  *source,
1728                    GFile                  *destination,
1729                    GFileCopyFlags          flags,
1730                    GCancellable           *cancellable,
1731                    GFileProgressCallback   progress_callback,
1732                    gpointer                progress_callback_data,
1733                    GError                **error)
1734 {
1735   /* Fall back to default copy */
1736   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
1737   return FALSE;
1738 }
1739
1740 static gboolean
1741 g_local_file_move (GFile                  *source,
1742                    GFile                  *destination,
1743                    GFileCopyFlags          flags,
1744                    GCancellable           *cancellable,
1745                    GFileProgressCallback   progress_callback,
1746                    gpointer                progress_callback_data,
1747                    GError                **error)
1748 {
1749   GLocalFile *local_source = G_LOCAL_FILE (source);
1750   GLocalFile *local_destination = G_LOCAL_FILE (destination);
1751   struct stat statbuf;
1752   gboolean destination_exist, source_is_dir;
1753   char *backup_name;
1754   int res;
1755
1756   res = g_lstat (local_source->filename, &statbuf);
1757   if (res == -1)
1758     {
1759       g_set_error (error, G_IO_ERROR,
1760                    g_io_error_from_errno (errno),
1761                    _("Error moving file: %s"),
1762                    g_strerror (errno));
1763       return FALSE;
1764     }
1765   else
1766     source_is_dir = S_ISDIR (statbuf.st_mode);
1767   
1768   destination_exist = FALSE;
1769   res = g_lstat (local_destination->filename, &statbuf);
1770   if (res == 0)
1771     {
1772       destination_exist = TRUE; /* Target file exists */
1773
1774       if (flags & G_FILE_COPY_OVERWRITE)
1775         {
1776           /* Always fail on dirs, even with overwrite */
1777           if (S_ISDIR (statbuf.st_mode))
1778             {
1779               g_set_error (error,
1780                            G_IO_ERROR,
1781                            G_IO_ERROR_WOULD_MERGE,
1782                            _("Can't move directory over directory"));
1783               return FALSE;
1784             }
1785         }
1786       else
1787         {
1788           g_set_error (error,
1789                        G_IO_ERROR,
1790                        G_IO_ERROR_EXISTS,
1791                        _("Target file already exists"));
1792           return FALSE;
1793         }
1794     }
1795   
1796   if (flags & G_FILE_COPY_BACKUP && destination_exist)
1797     {
1798       backup_name = g_strconcat (local_destination->filename, "~", NULL);
1799       if (rename (local_destination->filename, backup_name) == -1)
1800         {
1801           g_set_error (error,
1802                        G_IO_ERROR,
1803                        G_IO_ERROR_CANT_CREATE_BACKUP,
1804                        _("Backup file creation failed"));
1805           g_free (backup_name);
1806           return FALSE;
1807         }
1808       g_free (backup_name);
1809       destination_exist = FALSE; /* It did, but no more */
1810     }
1811
1812   if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
1813     {
1814       /* Source is a dir, destination exists (and is not a dir, because that would have failed
1815          earlier), and we're overwriting. Manually remove the target so we can do the rename. */
1816       res = unlink (local_destination->filename);
1817       if (res == -1)
1818         {
1819           g_set_error (error, G_IO_ERROR,
1820                        g_io_error_from_errno (errno),
1821                        _("Error removing target file: %s"),
1822                        g_strerror (errno));
1823           return FALSE;
1824         }
1825     }
1826   
1827   if (rename (local_source->filename, local_destination->filename) == -1)
1828     {
1829       int errsv = errno;
1830
1831       if (errsv == EXDEV)
1832         /* This will cause the fallback code to run */
1833         g_set_error (error, G_IO_ERROR,
1834                      G_IO_ERROR_NOT_SUPPORTED,
1835                      _("Move between mounts not supported"));
1836       else if (errsv == EINVAL)
1837         /* This must be an invalid filename, on e.g. FAT, or
1838            we're trying to move the file into itself...
1839            We return invalid filename for both... */
1840         g_set_error (error, G_IO_ERROR,
1841                      G_IO_ERROR_INVALID_FILENAME,
1842                      _("Invalid filename"));
1843       else
1844         g_set_error (error, G_IO_ERROR,
1845                      g_io_error_from_errno (errsv),
1846                      _("Error moving file: %s"),
1847                      g_strerror (errsv));
1848       return FALSE;
1849
1850     }
1851   return TRUE;
1852 }
1853
1854 static GFileMonitor*
1855 g_local_file_monitor_dir (GFile             *file,
1856                           GFileMonitorFlags  flags,
1857                           GCancellable      *cancellable)
1858 {
1859   GLocalFile* local_file = G_LOCAL_FILE(file);
1860   return _g_local_directory_monitor_new (local_file->filename, flags);
1861 }
1862
1863 static GFileMonitor*
1864 g_local_file_monitor_file (GFile             *file,
1865                            GFileMonitorFlags  flags,
1866                            GCancellable      *cancellable)
1867 {
1868   GLocalFile* local_file = G_LOCAL_FILE(file);
1869   return _g_local_file_monitor_new (local_file->filename, flags);
1870 }
1871
1872 static void
1873 g_local_file_file_iface_init (GFileIface *iface)
1874 {
1875   iface->dup = g_local_file_dup;
1876   iface->hash = g_local_file_hash;
1877   iface->equal = g_local_file_equal;
1878   iface->is_native = g_local_file_is_native;
1879   iface->has_uri_scheme = g_local_file_has_uri_scheme;
1880   iface->get_uri_scheme = g_local_file_get_uri_scheme;
1881   iface->get_basename = g_local_file_get_basename;
1882   iface->get_path = g_local_file_get_path;
1883   iface->get_uri = g_local_file_get_uri;
1884   iface->get_parse_name = g_local_file_get_parse_name;
1885   iface->get_parent = g_local_file_get_parent;
1886   iface->contains_file = g_local_file_contains_file;
1887   iface->get_relative_path = g_local_file_get_relative_path;
1888   iface->resolve_relative_path = g_local_file_resolve_relative_path;
1889   iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
1890   iface->set_display_name = g_local_file_set_display_name;
1891   iface->enumerate_children = g_local_file_enumerate_children;
1892   iface->query_info = g_local_file_query_info;
1893   iface->query_filesystem_info = g_local_file_query_filesystem_info;
1894   iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
1895   iface->query_settable_attributes = g_local_file_query_settable_attributes;
1896   iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
1897   iface->set_attribute = g_local_file_set_attribute;
1898   iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
1899   iface->read_fn = g_local_file_read;
1900   iface->append_to = g_local_file_append_to;
1901   iface->create = g_local_file_create;
1902   iface->replace = g_local_file_replace;
1903   iface->delete_file = g_local_file_delete;
1904   iface->trash = g_local_file_trash;
1905   iface->make_directory = g_local_file_make_directory;
1906   iface->make_symbolic_link = g_local_file_make_symbolic_link;
1907   iface->copy = g_local_file_copy;
1908   iface->move = g_local_file_move;
1909   iface->monitor_dir = g_local_file_monitor_dir;
1910   iface->monitor_file = g_local_file_monitor_file;
1911 }