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