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