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