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