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