1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Author: Alexander Larsson <alexl@redhat.com>
25 #include <sys/types.h>
36 #include <sys/statfs.h>
38 #if HAVE_SYS_STATVFS_H
39 #include <sys/statvfs.h>
43 #elif HAVE_SYS_MOUNT_H
45 #include <sys/param.h>
47 #include <sys/mount.h>
58 #include "gfileattribute.h"
59 #include "glocalfile.h"
60 #include "glocalfileinfo.h"
61 #include "glocalfileenumerator.h"
62 #include "glocalfileinputstream.h"
63 #include "glocalfileoutputstream.h"
64 #include "glocalfileiostream.h"
65 #include "glocalfilemonitor.h"
66 #include "gmountprivate.h"
67 #include "gunixmounts.h"
69 #include <glib/gstdio.h>
70 #include <glib/gstdioprivate.h>
73 #include "glib-unix.h"
74 #include "gportalsupport.h"
75 #include "gtrashportal.h"
78 #include "glib-private.h"
85 #ifndef FILE_READ_ONLY_VOLUME
86 #define FILE_READ_ONLY_VOLUME 0x00080000
90 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
93 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
96 #define S_ISLNK(m) (0)
100 #define ECANCELED 105
105 static void g_local_file_file_iface_init (GFileIface *iface);
107 static GFileAttributeInfoList *local_writable_attributes = NULL;
108 static GFileAttributeInfoList *local_writable_namespaces = NULL;
112 GObject parent_instance;
117 #define g_local_file_get_type _g_local_file_get_type
118 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
119 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
120 g_local_file_file_iface_init))
122 static char *find_mountpoint_for (const char *file, dev_t dev, gboolean resolve_basename_symlink);
125 static gboolean is_remote_fs_type (const gchar *fsname);
129 g_local_file_finalize (GObject *object)
133 local = G_LOCAL_FILE (object);
135 g_free (local->filename);
137 G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
141 g_local_file_class_init (GLocalFileClass *klass)
143 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
144 GFileAttributeInfoList *list;
146 gobject_class->finalize = g_local_file_finalize;
148 /* Set up attribute lists */
150 /* Writable attributes: */
152 list = g_file_attribute_info_list_new ();
154 g_file_attribute_info_list_add (list,
155 G_FILE_ATTRIBUTE_UNIX_MODE,
156 G_FILE_ATTRIBUTE_TYPE_UINT32,
157 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
158 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
161 g_file_attribute_info_list_add (list,
162 G_FILE_ATTRIBUTE_UNIX_UID,
163 G_FILE_ATTRIBUTE_TYPE_UINT32,
164 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
165 g_file_attribute_info_list_add (list,
166 G_FILE_ATTRIBUTE_UNIX_GID,
167 G_FILE_ATTRIBUTE_TYPE_UINT32,
168 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
172 g_file_attribute_info_list_add (list,
173 G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
174 G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
178 #if defined(HAVE_UTIMES) || defined(HAVE_UTIMENSAT)
179 g_file_attribute_info_list_add (list,
180 G_FILE_ATTRIBUTE_TIME_MODIFIED,
181 G_FILE_ATTRIBUTE_TYPE_UINT64,
182 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
183 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
184 g_file_attribute_info_list_add (list,
185 G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
186 G_FILE_ATTRIBUTE_TYPE_UINT32,
187 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
188 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
189 /* When copying, the target file is accessed. Replicating
190 * the source access time does not make sense in this case.
192 g_file_attribute_info_list_add (list,
193 G_FILE_ATTRIBUTE_TIME_ACCESS,
194 G_FILE_ATTRIBUTE_TYPE_UINT64,
195 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
196 g_file_attribute_info_list_add (list,
197 G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
198 G_FILE_ATTRIBUTE_TYPE_UINT32,
199 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
200 #endif /* HAVE_UTIMES || HAVE_UTIMENSAT */
202 #ifdef HAVE_UTIMENSAT
203 g_file_attribute_info_list_add (list,
204 G_FILE_ATTRIBUTE_TIME_MODIFIED_NSEC,
205 G_FILE_ATTRIBUTE_TYPE_UINT32,
206 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
207 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
208 g_file_attribute_info_list_add (list,
209 G_FILE_ATTRIBUTE_TIME_ACCESS_NSEC,
210 G_FILE_ATTRIBUTE_TYPE_UINT32,
211 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
214 local_writable_attributes = list;
218 g_local_file_init (GLocalFile *local)
223 _g_local_file_get_filename (GLocalFile *file)
225 return file->filename;
229 _g_local_file_new (const char *filename)
233 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
234 local->filename = g_canonicalize_filename (filename, NULL);
236 return G_FILE (local);
240 * g_local_file_new_from_dirname_and_basename:
241 * @dirname: an absolute, canonical directory name
242 * @basename: the name of a child inside @dirname
244 * Creates a #GFile from @dirname and @basename.
246 * This is more efficient than pasting the fields together for yourself
247 * and creating a #GFile from the result, and also more efficient than
248 * creating a #GFile for the dirname and using g_file_get_child().
250 * @dirname must be canonical, as per GLocalFile's opinion of what
251 * canonical means. This means that you should only pass strings that
252 * were returned by _g_local_file_get_filename().
257 g_local_file_new_from_dirname_and_basename (const gchar *dirname,
258 const gchar *basename)
262 g_return_val_if_fail (dirname != NULL, NULL);
263 g_return_val_if_fail (basename && basename[0] && !strchr (basename, '/'), NULL);
265 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
266 local->filename = g_build_filename (dirname, basename, NULL);
268 return G_FILE (local);
272 g_local_file_is_native (GFile *file)
278 g_local_file_has_uri_scheme (GFile *file,
279 const char *uri_scheme)
281 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
285 g_local_file_get_uri_scheme (GFile *file)
287 return g_strdup ("file");
291 g_local_file_get_basename (GFile *file)
293 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
297 g_local_file_get_path (GFile *file)
299 return g_strdup (G_LOCAL_FILE (file)->filename);
303 g_local_file_get_uri (GFile *file)
305 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
309 get_filename_charset (const gchar **filename_charset)
311 const gchar **charsets;
314 is_utf8 = g_get_filename_charsets (&charsets);
316 if (filename_charset)
317 *filename_charset = charsets[0];
323 name_is_valid_for_display (const char *string,
324 gboolean is_valid_utf8)
328 if (!is_valid_utf8 &&
329 !g_utf8_validate (string, -1, NULL))
332 while ((c = *string++) != 0)
334 if (g_ascii_iscntrl (c))
342 g_local_file_get_parse_name (GFile *file)
344 const char *filename;
346 const gchar *charset;
348 char *roundtripped_filename;
349 gboolean free_utf8_filename;
350 gboolean is_valid_utf8;
353 filename = G_LOCAL_FILE (file)->filename;
354 if (get_filename_charset (&charset))
356 utf8_filename = (char *)filename;
357 free_utf8_filename = FALSE;
358 is_valid_utf8 = FALSE; /* Can't guarantee this */
362 utf8_filename = g_convert (filename, -1,
363 "UTF-8", charset, NULL, NULL, NULL);
364 free_utf8_filename = TRUE;
365 is_valid_utf8 = TRUE;
367 if (utf8_filename != NULL)
369 /* Make sure we can roundtrip: */
370 roundtripped_filename = g_convert (utf8_filename, -1,
371 charset, "UTF-8", NULL, NULL, NULL);
373 if (roundtripped_filename == NULL ||
374 strcmp (filename, roundtripped_filename) != 0)
376 g_free (utf8_filename);
377 utf8_filename = NULL;
380 g_free (roundtripped_filename);
384 if (utf8_filename != NULL &&
385 name_is_valid_for_display (utf8_filename, is_valid_utf8))
387 if (free_utf8_filename)
388 parse_name = utf8_filename;
390 parse_name = g_strdup (utf8_filename);
395 char *dup_filename, *p, *backslash;
397 /* Turn backslashes into forward slashes like
398 * g_filename_to_uri() would do (but we can't use that because
399 * it doesn't output IRIs).
401 dup_filename = g_strdup (filename);
402 filename = p = dup_filename;
404 while ((backslash = strchr (p, '\\')) != NULL)
411 escaped_path = g_uri_escape_string (filename,
412 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
414 parse_name = g_strconcat ("file://",
415 (*escaped_path != '/') ? "/" : "",
419 g_free (escaped_path);
421 g_free (dup_filename);
423 if (free_utf8_filename)
424 g_free (utf8_filename);
431 g_local_file_get_parent (GFile *file)
433 GLocalFile *local = G_LOCAL_FILE (file);
434 const char *non_root;
438 /* Check for root; local->filename is guaranteed to be absolute, so
439 * g_path_skip_root() should never return NULL. */
440 non_root = g_path_skip_root (local->filename);
441 g_assert (non_root != NULL);
446 dirname = g_path_get_dirname (local->filename);
447 parent = _g_local_file_new (dirname);
453 g_local_file_dup (GFile *file)
455 GLocalFile *local = G_LOCAL_FILE (file);
457 return _g_local_file_new (local->filename);
461 g_local_file_hash (GFile *file)
463 GLocalFile *local = G_LOCAL_FILE (file);
465 return g_str_hash (local->filename);
469 g_local_file_equal (GFile *file1,
472 GLocalFile *local1 = G_LOCAL_FILE (file1);
473 GLocalFile *local2 = G_LOCAL_FILE (file2);
475 return g_str_equal (local1->filename, local2->filename);
479 match_prefix (const char *path,
484 prefix_len = strlen (prefix);
485 if (strncmp (path, prefix, prefix_len) != 0)
488 /* Handle the case where prefix is the root, so that
489 * the IS_DIR_SEPRARATOR check below works */
490 if (prefix_len > 0 &&
491 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
494 return path + prefix_len;
498 g_local_file_prefix_matches (GFile *parent,
501 GLocalFile *parent_local = G_LOCAL_FILE (parent);
502 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
503 const char *remainder;
505 remainder = match_prefix (descendant_local->filename, parent_local->filename);
506 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
512 g_local_file_get_relative_path (GFile *parent,
515 GLocalFile *parent_local = G_LOCAL_FILE (parent);
516 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
517 const char *remainder;
519 remainder = match_prefix (descendant_local->filename, parent_local->filename);
521 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
522 return g_strdup (remainder + 1);
527 g_local_file_resolve_relative_path (GFile *file,
528 const char *relative_path)
530 GLocalFile *local = G_LOCAL_FILE (file);
534 if (g_path_is_absolute (relative_path))
535 return _g_local_file_new (relative_path);
537 filename = g_build_filename (local->filename, relative_path, NULL);
538 child = _g_local_file_new (filename);
544 static GFileEnumerator *
545 g_local_file_enumerate_children (GFile *file,
546 const char *attributes,
547 GFileQueryInfoFlags flags,
548 GCancellable *cancellable,
551 GLocalFile *local = G_LOCAL_FILE (file);
552 return _g_local_file_enumerator_new (local,
558 g_local_file_get_child_for_display_name (GFile *file,
559 const char *display_name,
565 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
566 if (basename == NULL)
568 g_set_error (error, G_IO_ERROR,
569 G_IO_ERROR_INVALID_FILENAME,
570 _("Invalid filename %s"), display_name);
574 new_file = g_file_get_child (file, basename);
580 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
582 get_fs_type (long f_type)
584 /* filesystem ids taken from linux manpage */
602 return "binfmt_misc";
606 return "btrfs_test_fs";
763 G_LOCK_DEFINE_STATIC(mount_info_hash);
764 static GHashTable *mount_info_hash = NULL;
765 static guint64 mount_info_hash_cache_time = 0;
768 MOUNT_INFO_READONLY = 1<<0
772 device_equal (gconstpointer v1,
775 return *(dev_t *)v1 == *(dev_t *)v2;
779 device_hash (gconstpointer v)
781 return (guint) *(dev_t *)v;
785 get_mount_info (GFileInfo *fs_info,
787 GFileAttributeMatcher *matcher)
791 gpointer info_as_ptr;
795 GUnixMountEntry *mount;
797 gboolean is_remote = FALSE;
799 if (g_lstat (path, &buf) != 0)
802 G_LOCK (mount_info_hash);
804 if (mount_info_hash == NULL)
805 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
809 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
810 g_hash_table_remove_all (mount_info_hash);
812 got_info = g_hash_table_lookup_extended (mount_info_hash,
817 G_UNLOCK (mount_info_hash);
819 mount_info = GPOINTER_TO_UINT (info_as_ptr);
825 mountpoint = find_mountpoint_for (path, buf.st_dev, FALSE);
826 if (mountpoint == NULL)
827 mountpoint = g_strdup ("/");
829 mount = g_unix_mount_at (mountpoint, &cache_time);
832 if (g_unix_mount_is_readonly (mount))
833 mount_info |= MOUNT_INFO_READONLY;
834 if (is_remote_fs_type (g_unix_mount_get_fs_type (mount)))
837 g_unix_mount_free (mount);
842 dev = g_new0 (dev_t, 1);
845 G_LOCK (mount_info_hash);
846 mount_info_hash_cache_time = cache_time;
847 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
848 G_UNLOCK (mount_info_hash);
851 if (g_file_attribute_matcher_matches (matcher,
852 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
853 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
854 (mount_info & MOUNT_INFO_READONLY));
856 if (g_file_attribute_matcher_matches (matcher,
857 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
858 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE, is_remote);
866 get_volume_for_path (const char *path)
872 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
873 result = g_new (wchar_t, MAX_PATH);
875 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
877 char *msg = g_win32_error_message (GetLastError ());
878 g_critical ("GetVolumePathName failed: %s", msg);
885 len = wcslen (result);
886 if (len > 0 && result[len-1] != L'\\')
888 result = g_renew (wchar_t, result, len + 2);
898 find_mountpoint_for (const char *file, dev_t dev, gboolean resolve_basename_symlink)
903 wpath = get_volume_for_path (file);
907 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
914 get_filesystem_readonly (GFileInfo *info,
919 rootdir = get_volume_for_path (path);
924 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
925 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
926 (flags & FILE_READ_ONLY_VOLUME) != 0);
932 #endif /* G_OS_WIN32 */
934 #pragma GCC diagnostic push
935 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
937 g_set_io_error (GError **error,
942 GLocalFile *local = G_LOCAL_FILE (file);
945 display_name = g_filename_display_name (local->filename);
946 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
947 msg, display_name, g_strerror (errsv));
948 g_free (display_name);
950 #pragma GCC diagnostic pop
953 g_local_file_query_filesystem_info (GFile *file,
954 const char *attributes,
955 GCancellable *cancellable,
958 GLocalFile *local = G_LOCAL_FILE (file);
960 int statfs_result = 0;
966 struct statfs statfs_buffer;
967 #elif defined(USE_STATVFS)
969 struct statvfs statfs_buffer;
970 #endif /* USE_STATFS */
971 #endif /* G_OS_WIN32 */
972 GFileAttributeMatcher *attribute_matcher;
979 statfs_result = statfs (local->filename, &statfs_buffer);
980 #elif STATFS_ARGS == 4
981 statfs_result = statfs (local->filename, &statfs_buffer,
982 sizeof (statfs_buffer), 0);
983 #endif /* STATFS_ARGS == 2 */
984 block_size = statfs_buffer.f_bsize;
986 /* Many backends can't report free size (for instance the gvfs fuse
987 * backend for backend not supporting this), and set f_bfree to 0,
988 * but it can be 0 for real too. We treat the available == 0 and
989 * free == 0 case as "both of these are invalid", but only on file systems
990 * which are known to not support this (otherwise we can omit metadata for
991 * systems which are legitimately full). */
992 #if defined(__linux__)
993 if (statfs_result == 0 &&
994 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
995 (/* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
996 statfs_buffer.f_type == 0x564c ||
997 /* man statfs: FUSE_SUPER_MAGIC == 0x65735546 */
998 statfs_buffer.f_type == 0x65735546))
1000 #endif /* __linux__ */
1002 #elif defined(USE_STATVFS)
1003 statfs_result = statvfs (local->filename, &statfs_buffer);
1004 block_size = statfs_buffer.f_frsize;
1005 #endif /* USE_STATFS */
1007 if (statfs_result == -1)
1011 g_set_io_error (error,
1012 _("Error getting filesystem info for %s: %s"),
1017 info = g_file_info_new ();
1019 attribute_matcher = g_file_attribute_matcher_new (attributes);
1022 g_file_attribute_matcher_matches (attribute_matcher,
1023 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1026 gchar *localdir = g_path_get_dirname (local->filename);
1027 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1031 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1032 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1035 #if defined(USE_STATFS) || defined(USE_STATVFS)
1036 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1041 g_file_attribute_matcher_matches (attribute_matcher,
1042 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1045 gchar *localdir = g_path_get_dirname (local->filename);
1046 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1050 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1051 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1054 #if defined(USE_STATFS) || defined(USE_STATVFS)
1055 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1057 #endif /* G_OS_WIN32 */
1061 g_file_attribute_matcher_matches (attribute_matcher,
1062 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1065 gchar *localdir = g_path_get_dirname (local->filename);
1066 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1067 ULARGE_INTEGER li_free;
1068 ULARGE_INTEGER li_total;
1071 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1072 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1075 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1076 #endif /* G_OS_WIN32 */
1081 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1082 fstype = statfs_buffer.f_fstypename;
1084 fstype = get_fs_type (statfs_buffer.f_type);
1087 #elif defined(USE_STATVFS)
1088 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1089 fstype = statfs_buffer.f_fstypename;
1090 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1091 fstype = statfs_buffer.f_basetype;
1092 #elif defined(HAVE_STRUCT_STATVFS_F_TYPE)
1093 fstype = get_fs_type (statfs_buffer.f_type);
1097 #endif /* USE_STATFS */
1100 g_file_attribute_matcher_matches (attribute_matcher,
1101 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1102 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1103 #endif /* G_OS_WIN32 */
1105 if (g_file_attribute_matcher_matches (attribute_matcher,
1106 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY) ||
1107 g_file_attribute_matcher_matches (attribute_matcher,
1108 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
1111 get_filesystem_readonly (info, local->filename);
1113 get_mount_info (info, local->filename, attribute_matcher);
1114 #endif /* G_OS_WIN32 */
1117 g_file_attribute_matcher_unref (attribute_matcher);
1123 g_local_file_find_enclosing_mount (GFile *file,
1124 GCancellable *cancellable,
1127 GLocalFile *local = G_LOCAL_FILE (file);
1132 if (g_lstat (local->filename, &buf) != 0)
1135 mountpoint = find_mountpoint_for (local->filename, buf.st_dev, FALSE);
1136 if (mountpoint == NULL)
1139 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1140 g_free (mountpoint);
1145 g_set_io_error (error,
1146 /* Translators: This is an error message when trying to find
1147 * the enclosing (user visible) mount of a file, but none
1150 _("Containing mount for file %s not found"),
1157 g_local_file_set_display_name (GFile *file,
1158 const char *display_name,
1159 GCancellable *cancellable,
1162 GLocalFile *local, *new_local;
1163 GFile *new_file, *parent;
1169 parent = g_file_get_parent (file);
1172 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1173 _("Can’t rename root directory"));
1177 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1178 g_object_unref (parent);
1180 if (new_file == NULL)
1182 local = G_LOCAL_FILE (file);
1183 new_local = G_LOCAL_FILE (new_file);
1185 if (g_lstat (new_local->filename, &statbuf) == -1)
1189 if (errsv != ENOENT)
1191 g_set_io_error (error, _("Error renaming file %s: %s"), new_file, errsv);
1197 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
1198 _("Can’t rename file, filename already exists"));
1202 if (g_rename (local->filename, new_local->filename) == -1)
1206 if (errsv == EINVAL)
1207 /* We can't get a rename file into itself error here,
1208 * so this must be an invalid filename, on e.g. FAT
1210 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME,
1211 _("Invalid filename"));
1213 g_set_io_error (error,
1214 _("Error renaming file %s: %s"),
1216 g_object_unref (new_file);
1220 vfs = g_vfs_get_default ();
1221 class = G_VFS_GET_CLASS (vfs);
1222 if (class->local_file_moved)
1223 class->local_file_moved (vfs, local->filename, new_local->filename);
1229 g_local_file_query_info (GFile *file,
1230 const char *attributes,
1231 GFileQueryInfoFlags flags,
1232 GCancellable *cancellable,
1235 GLocalFile *local = G_LOCAL_FILE (file);
1237 GFileAttributeMatcher *matcher;
1238 char *basename, *dirname;
1239 GLocalParentFileInfo parent_info;
1241 matcher = g_file_attribute_matcher_new (attributes);
1243 basename = g_path_get_basename (local->filename);
1245 dirname = g_path_get_dirname (local->filename);
1246 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1249 info = _g_local_file_info_get (basename, local->filename,
1250 matcher, flags, &parent_info,
1254 _g_local_file_info_free_parent_info (&parent_info);
1257 g_file_attribute_matcher_unref (matcher);
1262 static GFileAttributeInfoList *
1263 g_local_file_query_settable_attributes (GFile *file,
1264 GCancellable *cancellable,
1267 return g_file_attribute_info_list_ref (local_writable_attributes);
1270 static GFileAttributeInfoList *
1271 g_local_file_query_writable_namespaces (GFile *file,
1272 GCancellable *cancellable,
1275 GFileAttributeInfoList *list;
1279 if (g_once_init_enter_pointer (&local_writable_namespaces))
1281 /* Writable namespaces: */
1283 list = g_file_attribute_info_list_new ();
1286 g_file_attribute_info_list_add (list,
1288 G_FILE_ATTRIBUTE_TYPE_STRING,
1289 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1290 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1291 g_file_attribute_info_list_add (list,
1293 G_FILE_ATTRIBUTE_TYPE_STRING,
1294 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1297 vfs = g_vfs_get_default ();
1298 class = G_VFS_GET_CLASS (vfs);
1299 if (class->add_writable_namespaces)
1300 class->add_writable_namespaces (vfs, list);
1302 g_once_init_leave_pointer (&local_writable_namespaces, list);
1304 list = (GFileAttributeInfoList *)local_writable_namespaces;
1306 return g_file_attribute_info_list_ref (list);
1310 g_local_file_set_attribute (GFile *file,
1311 const char *attribute,
1312 GFileAttributeType type,
1314 GFileQueryInfoFlags flags,
1315 GCancellable *cancellable,
1318 GLocalFile *local = G_LOCAL_FILE (file);
1320 return _g_local_file_info_set_attribute (local->filename,
1330 g_local_file_set_attributes_from_info (GFile *file,
1332 GFileQueryInfoFlags flags,
1333 GCancellable *cancellable,
1336 GLocalFile *local = G_LOCAL_FILE (file);
1337 int res, chained_res;
1338 GFileIface *default_iface;
1340 res = _g_local_file_info_set_attributes (local->filename,
1346 error = NULL; /* Don't write over error if further errors */
1348 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1350 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1352 return res && chained_res;
1355 static GFileInputStream *
1356 g_local_file_read (GFile *file,
1357 GCancellable *cancellable,
1360 GLocalFile *local = G_LOCAL_FILE (file);
1364 fd = g_open (local->filename, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
1370 if (errsv == EACCES)
1372 /* Exploit the fact that on W32 the glib filename encoding is UTF8 */
1373 ret = GLIB_PRIVATE_CALL (g_win32_stat_utf8) (local->filename, &buf);
1374 if (ret == 0 && S_ISDIR (buf.st_mode))
1378 g_set_io_error (error,
1379 _("Error opening file %s: %s"),
1384 ret = g_local_file_fstat (fd, G_LOCAL_FILE_STAT_FIELD_TYPE, G_LOCAL_FILE_STAT_FIELD_ALL, &buf);
1386 if (ret == 0 && S_ISDIR (_g_stat_mode (&buf)))
1388 (void) g_close (fd, NULL);
1389 g_set_io_error (error,
1390 _("Error opening file %s: %s"),
1395 return _g_local_file_input_stream_new (fd);
1398 static GFileOutputStream *
1399 g_local_file_append_to (GFile *file,
1400 GFileCreateFlags flags,
1401 GCancellable *cancellable,
1404 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1405 flags, cancellable, error);
1408 static GFileOutputStream *
1409 g_local_file_create (GFile *file,
1410 GFileCreateFlags flags,
1411 GCancellable *cancellable,
1414 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1416 cancellable, error);
1419 static GFileOutputStream *
1420 g_local_file_replace (GFile *file,
1422 gboolean make_backup,
1423 GFileCreateFlags flags,
1424 GCancellable *cancellable,
1427 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1429 etag, make_backup, flags, NULL,
1430 cancellable, error);
1433 static GFileIOStream *
1434 g_local_file_open_readwrite (GFile *file,
1435 GCancellable *cancellable,
1438 GFileOutputStream *output;
1441 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1443 cancellable, error);
1447 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1448 g_object_unref (output);
1452 static GFileIOStream *
1453 g_local_file_create_readwrite (GFile *file,
1454 GFileCreateFlags flags,
1455 GCancellable *cancellable,
1458 GFileOutputStream *output;
1461 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1463 cancellable, error);
1467 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1468 g_object_unref (output);
1472 static GFileIOStream *
1473 g_local_file_replace_readwrite (GFile *file,
1475 gboolean make_backup,
1476 GFileCreateFlags flags,
1477 GCancellable *cancellable,
1480 GFileOutputStream *output;
1483 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1485 etag, make_backup, flags, NULL,
1486 cancellable, error);
1490 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1491 g_object_unref (output);
1496 g_local_file_delete (GFile *file,
1497 GCancellable *cancellable,
1500 GLocalFile *local = G_LOCAL_FILE (file);
1504 if (g_remove (local->filename) == -1)
1508 /* Posix allows EEXIST too, but the clearer error
1509 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1511 if (errsv == EEXIST)
1514 g_set_io_error (error,
1515 _("Error removing file %s: %s"),
1520 vfs = g_vfs_get_default ();
1521 class = G_VFS_GET_CLASS (vfs);
1522 if (class->local_file_removed)
1523 class->local_file_removed (vfs, local->filename);
1531 strip_trailing_slashes (const char *path)
1536 path_copy = g_strdup (path);
1537 len = strlen (path_copy);
1538 while (len > 1 && path_copy[len-1] == '/')
1539 path_copy[--len] = 0;
1545 expand_symlink (const char *link)
1547 char *resolved, *canonical, *parent, *link2;
1548 char symlink_value[4096];
1556 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1559 return g_strdup (link);
1560 symlink_value[res] = 0;
1563 if (g_path_is_absolute (symlink_value))
1564 return g_canonicalize_filename (symlink_value, NULL);
1567 link2 = strip_trailing_slashes (link);
1568 parent = g_path_get_dirname (link2);
1571 resolved = g_build_filename (parent, symlink_value, NULL);
1574 canonical = g_canonicalize_filename (resolved, NULL);
1583 expand_symlinks (const char *path,
1587 GStatBuf target_stat;
1590 target = g_strdup (path);
1595 if (g_lstat (target, &target_stat) != 0)
1601 if (S_ISLNK (target_stat.st_mode))
1604 target = expand_symlink (target);
1611 if (num_recursions > MAXSYMLINKS)
1613 /* 40 is used in kernel sources currently:
1614 * https://github.com/torvalds/linux/include/linux/namei.h
1616 if (num_recursions > 40)
1623 while (S_ISLNK (target_stat.st_mode));
1626 *dev = target_stat.st_dev;
1632 get_parent (const char *path,
1638 path_copy = strip_trailing_slashes (path);
1640 parent = g_path_get_dirname (path_copy);
1641 if (strcmp (parent, ".") == 0)
1649 res = expand_symlinks (parent, parent_dev);
1656 expand_all_symlinks (const char *path)
1658 char *parent, *parent_expanded;
1659 char *basename, *res;
1662 parent = get_parent (path, &parent_dev);
1666 if (g_strcmp0 (parent, "/") != 0)
1668 parent_expanded = expand_all_symlinks (parent);
1669 basename = g_path_get_basename (path);
1670 res = g_build_filename (parent_expanded, basename, NULL);
1672 g_free (parent_expanded);
1675 res = g_strdup (path);
1683 find_mountpoint_for (const char *file,
1685 gboolean resolve_basename_symlink)
1688 dev_t dir_dev, parent_dev;
1690 if (resolve_basename_symlink)
1692 dir = expand_symlinks (file, NULL);
1697 dir = g_strdup (file);
1701 while (g_strcmp0 (dir, "/") != 0)
1703 parent = get_parent (dir, &parent_dev);
1710 if (parent_dev != dir_dev)
1724 _g_local_file_find_topdir_for (const char *file)
1727 char *mountpoint = NULL;
1730 dir = get_parent (file, &dir_dev);
1734 mountpoint = find_mountpoint_for (dir, dir_dev, TRUE);
1741 get_unique_filename (const char *basename,
1747 return g_strdup (basename);
1749 dot = strchr (basename, '.');
1751 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1753 return g_strdup_printf ("%s.%d", basename, id);
1757 path_has_prefix (const char *path,
1765 prefix_len = strlen (prefix);
1767 if (strncmp (path, prefix, prefix_len) == 0 &&
1768 (prefix_len == 0 || /* empty prefix always matches */
1769 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1770 path[prefix_len] == 0 ||
1771 path[prefix_len] == '/'))
1778 try_make_relative (const char *path,
1781 char *path2, *base2;
1784 path2 = expand_all_symlinks (path);
1785 base2 = expand_all_symlinks (base);
1788 if (path2 != NULL && base2 != NULL && path_has_prefix (path2, base2))
1790 relative = path2 + strlen (base2);
1791 while (*relative == '/')
1793 relative = g_strdup (relative);
1801 /* Failed, use abs path */
1802 return g_strdup (path);
1806 ignore_trash_mount (GUnixMountEntry *mount)
1808 GUnixMountPoint *mount_point = NULL;
1809 const gchar *mount_options;
1810 gboolean retval = TRUE;
1812 if (g_unix_mount_is_system_internal (mount))
1815 mount_options = g_unix_mount_get_options (mount);
1816 if (mount_options == NULL)
1818 mount_point = g_unix_mount_point_at (g_unix_mount_get_mount_path (mount),
1820 if (mount_point != NULL)
1821 mount_options = g_unix_mount_point_get_options (mount_point);
1824 if (mount_options == NULL ||
1825 strstr (mount_options, "x-gvfs-notrash") == NULL)
1828 g_clear_pointer (&mount_point, g_unix_mount_point_free);
1834 ignore_trash_path (const gchar *topdir)
1836 GUnixMountEntry *mount;
1837 gboolean retval = TRUE;
1839 mount = g_unix_mount_at (topdir, NULL);
1843 retval = ignore_trash_mount (mount);
1846 g_clear_pointer (&mount, g_unix_mount_free);
1852 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1854 static gsize home_dev_set = 0;
1855 static dev_t home_dev;
1856 static gboolean home_dev_valid = FALSE;
1857 char *topdir, *globaldir, *trashdir, *tmpname;
1860 GStatBuf global_stat, trash_stat;
1863 if (g_once_init_enter (&home_dev_set))
1867 if (g_stat (g_get_home_dir (), &home_stat) == 0)
1869 home_dev = home_stat.st_dev;
1870 home_dev_valid = TRUE;
1874 home_dev_valid = FALSE;
1877 g_once_init_leave (&home_dev_set, 1);
1880 /* Assume we can trash to the home */
1881 if (!home_dev_valid)
1883 else if (dir_dev == home_dev)
1886 topdir = find_mountpoint_for (dirname, dir_dev, TRUE);
1890 if (ignore_trash_path (topdir))
1897 globaldir = g_build_filename (topdir, ".Trash", NULL);
1898 if (g_lstat (globaldir, &global_stat) == 0 &&
1899 S_ISDIR (global_stat.st_mode) &&
1900 (global_stat.st_mode & S_ISVTX) != 0)
1902 /* got a toplevel sysadmin created dir, assume we
1903 * can trash to it (we should be able to create a dir)
1904 * This fails for the FAT case where the ownership of
1905 * that dir would be wrong though..
1913 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1915 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1917 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1918 trashdir = g_build_filename (topdir, tmpname, NULL);
1921 if (g_lstat (trashdir, &trash_stat) == 0)
1925 return S_ISDIR (trash_stat.st_mode) &&
1926 trash_stat.st_uid == uid;
1930 /* User specific trash didn't exist, can we create it? */
1931 res = g_access (topdir, W_OK) == 0;
1939 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1941 gboolean ret = FALSE;
1942 gchar *mount_dir = NULL;
1943 size_t mount_dir_len;
1946 if (!g_str_has_suffix (path, "/lost+found"))
1949 mount_dir = find_mountpoint_for (path, path_dev, FALSE);
1950 if (mount_dir == NULL)
1953 mount_dir_len = strlen (mount_dir);
1954 /* We special-case rootfs ('/') since it's the only case where
1955 * mount_dir ends in '/'
1957 if (mount_dir_len == 1)
1959 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1962 if (g_lstat (path, &statbuf) != 0)
1965 if (!(S_ISDIR (statbuf.st_mode) &&
1966 statbuf.st_uid == 0 &&
1967 statbuf.st_gid == 0))
1979 g_local_file_trash (GFile *file,
1980 GCancellable *cancellable,
1983 GLocalFile *local = G_LOCAL_FILE (file);
1984 GStatBuf file_stat, home_stat;
1985 const char *homedir;
1986 char *trashdir, *topdir, *infodir, *filesdir;
1987 char *basename, *trashname, *trashfile, *infoname, *infofile;
1988 char *original_name, *original_name_escaped;
1992 gboolean is_homedir_trash;
1993 char *delete_time = NULL;
1995 GStatBuf trash_stat, global_stat;
1996 char *dirname, *globaldir;
2001 if (glib_should_use_portal ())
2002 return g_trash_portal_trash_file (file, error);
2004 if (g_lstat (local->filename, &file_stat) != 0)
2008 g_set_io_error (error,
2009 _("Error trashing file %s: %s"),
2014 homedir = g_get_home_dir ();
2015 if (g_stat (homedir, &home_stat) != 0)
2019 g_set_io_error (error,
2020 _("Error trashing file %s: %s"),
2025 is_homedir_trash = FALSE;
2028 /* On overlayfs, a file's st_dev will be different to the home directory's.
2029 * We still want to create our trash directory under the home directory, so
2030 * instead we should stat the directory that the file we're deleting is in as
2031 * this will have the same st_dev.
2033 if (!S_ISDIR (file_stat.st_mode))
2035 path = g_path_get_dirname (local->filename);
2036 /* If the parent is a symlink to a different device then it might have
2037 * st_dev equal to the home directory's, in which case we will end up
2038 * trying to rename across a filesystem boundary, which doesn't work. So
2039 * we use g_stat here instead of g_lstat, to know where the symlink
2041 if (g_stat (path, &file_stat))
2046 g_set_io_error (error,
2047 _("Error trashing file %s: %s"),
2054 if (file_stat.st_dev == home_stat.st_dev)
2056 is_homedir_trash = TRUE;
2058 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
2059 if (g_mkdir_with_parents (trashdir, 0700) < 0)
2064 display_name = g_filename_display_name (trashdir);
2065 g_set_error (error, G_IO_ERROR,
2066 g_io_error_from_errno (errsv),
2067 _("Unable to create trash directory %s: %s"),
2068 display_name, g_strerror (errsv));
2069 g_free (display_name);
2073 topdir = g_strdup (g_get_user_data_dir ());
2079 gboolean success = FALSE;
2082 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
2084 topdir = _g_local_file_find_topdir_for (local->filename);
2087 g_set_io_error (error,
2088 _("Unable to find toplevel directory to trash %s"),
2093 if (ignore_trash_path (topdir))
2095 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2096 _("Trashing on system internal mounts is not supported"));
2102 /* Try looking for global trash dir $topdir/.Trash/$uid */
2103 globaldir = g_build_filename (topdir, ".Trash", NULL);
2104 if (g_lstat (globaldir, &global_stat) == 0 &&
2105 S_ISDIR (global_stat.st_mode) &&
2106 (global_stat.st_mode & S_ISVTX) != 0)
2108 trashdir = g_build_filename (globaldir, uid_str, NULL);
2111 if (g_lstat (trashdir, &trash_stat) == 0)
2113 if (!S_ISDIR (trash_stat.st_mode) ||
2114 trash_stat.st_uid != uid)
2116 /* Not a directory or not owned by user, ignore */
2122 else if (g_mkdir (trashdir, 0700) == -1)
2131 if (trashdir == NULL)
2133 gboolean tried_create;
2135 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2136 dirname = g_strdup_printf (".Trash-%s", uid_str);
2137 trashdir = g_build_filename (topdir, dirname, NULL);
2141 tried_create = FALSE;
2144 if (g_lstat (trashdir, &trash_stat) == 0)
2146 if (!S_ISDIR (trash_stat.st_mode) ||
2147 trash_stat.st_uid != uid)
2149 /* Remove the failed directory */
2151 g_remove (trashdir);
2153 /* Not a directory or not owned by user, ignore */
2159 if (!tried_create &&
2160 g_mkdir (trashdir, 0700) != -1)
2162 /* Ensure that the created dir has the right uid etc.
2163 This might fail on e.g. a FAT dir */
2164 tried_create = TRUE;
2176 gchar *trashdir_display_name = NULL, *file_display_name = NULL;
2178 trashdir_display_name = g_filename_display_name (trashdir);
2179 file_display_name = g_filename_display_name (local->filename);
2180 g_set_error (error, G_IO_ERROR,
2181 G_IO_ERROR_NOT_SUPPORTED,
2182 _("Unable to find or create trash directory %s to trash %s"),
2183 trashdir_display_name, file_display_name);
2185 g_free (trashdir_display_name);
2186 g_free (file_display_name);
2195 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2197 infodir = g_build_filename (trashdir, "info", NULL);
2198 filesdir = g_build_filename (trashdir, "files", NULL);
2200 /* Make sure we have the subdirectories */
2201 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2202 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2204 gchar *trashdir_display_name = NULL, *file_display_name = NULL;
2206 trashdir_display_name = g_filename_display_name (trashdir);
2207 file_display_name = g_filename_display_name (local->filename);
2208 g_set_error (error, G_IO_ERROR,
2209 G_IO_ERROR_NOT_SUPPORTED,
2210 _("Unable to find or create trash directory %s to trash %s"),
2211 trashdir_display_name, file_display_name);
2213 g_free (trashdir_display_name);
2214 g_free (file_display_name);
2226 basename = g_path_get_basename (local->filename);
2234 trashname = get_unique_filename (basename, i++);
2235 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2236 infofile = g_build_filename (infodir, infoname, NULL);
2239 fd = g_open (infofile, O_CREAT | O_EXCL | O_CLOEXEC, 0666);
2241 } while (fd == -1 && errsv == EEXIST);
2253 g_set_io_error (error,
2254 _("Unable to create trashing info file for %s: %s"),
2259 (void) g_close (fd, NULL);
2261 /* Write the full content of the info file before trashing to make
2262 * sure someone doesn't read an empty file. See #749314
2265 /* Use absolute names for homedir */
2266 if (is_homedir_trash)
2267 original_name = g_strdup (local->filename);
2269 original_name = try_make_relative (local->filename, topdir);
2270 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2272 g_free (original_name);
2276 GDateTime *now = g_date_time_new_now_local ();
2278 delete_time = g_date_time_format (now, "%Y-%m-%dT%H:%M:%S");
2280 delete_time = g_strdup ("9999-12-31T23:59:59");
2281 g_date_time_unref (now);
2284 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2285 original_name_escaped, delete_time);
2286 g_free (delete_time);
2287 g_clear_pointer (&original_name_escaped, g_free);
2289 if (!g_file_set_contents_full (infofile, data, -1,
2290 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
2293 g_unlink (infofile);
2303 g_clear_pointer (&data, g_free);
2305 /* TODO: Maybe we should verify that you can delete the file from the trash
2306 * before moving it? OTOH, that is hard, as it needs a recursive scan
2309 trashfile = g_build_filename (filesdir, trashname, NULL);
2313 if (g_rename (local->filename, trashfile) == -1)
2317 g_unlink (infofile);
2324 /* The trash dir was actually on another fs anyway!?
2325 * This can happen when the same device is mounted multiple
2326 * times, or with bind mounts of the same fs.
2328 g_set_io_error (error,
2329 _("Unable to trash file %s across filesystem boundaries"),
2332 g_set_io_error (error,
2333 _("Unable to trash file %s: %s"),
2338 vfs = g_vfs_get_default ();
2339 class = G_VFS_GET_CLASS (vfs);
2340 if (class->local_file_moved)
2341 class->local_file_moved (vfs, local->filename, trashfile);
2345 /* TODO: Do we need to update mtime/atime here after the move? */
2352 #else /* G_OS_WIN32 */
2354 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2356 return FALSE; /* XXX ??? */
2360 g_local_file_trash (GFile *file,
2361 GCancellable *cancellable,
2364 GLocalFile *local = G_LOCAL_FILE (file);
2365 SHFILEOPSTRUCTW op = {0};
2370 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2371 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2372 wfilename = g_renew (wchar_t, wfilename, len + 2);
2373 wfilename[len + 1] = 0;
2375 op.wFunc = FO_DELETE;
2376 op.pFrom = wfilename;
2377 op.fFlags = FOF_ALLOWUNDO;
2379 success = SHFileOperationW (&op) == 0;
2381 if (success && op.fAnyOperationsAborted)
2383 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2384 g_cancellable_cancel (cancellable);
2385 g_set_io_error (error,
2386 _("Unable to trash file %s: %s"),
2391 g_set_io_error (error,
2392 _("Unable to trash file %s"),
2398 #endif /* G_OS_WIN32 */
2401 g_local_file_make_directory (GFile *file,
2402 GCancellable *cancellable,
2405 GLocalFile *local = G_LOCAL_FILE (file);
2407 if (g_mkdir (local->filename, 0777) == -1)
2411 if (errsv == EINVAL)
2412 /* This must be an invalid filename, on e.g. FAT */
2413 g_set_error_literal (error, G_IO_ERROR,
2414 G_IO_ERROR_INVALID_FILENAME,
2415 _("Invalid filename"));
2417 g_set_io_error (error,
2418 _("Error creating directory %s: %s"),
2428 g_local_file_make_symbolic_link (GFile *file,
2429 const char *symlink_value,
2430 GCancellable *cancellable,
2433 GLocalFile *local = G_LOCAL_FILE (file);
2435 if (symlink (symlink_value, local->filename) == -1)
2439 if (errsv == EINVAL)
2440 /* This must be an invalid filename, on e.g. FAT */
2441 g_set_error_literal (error, G_IO_ERROR,
2442 G_IO_ERROR_INVALID_FILENAME,
2443 _("Invalid filename"));
2444 else if (errsv == EPERM)
2445 g_set_error (error, G_IO_ERROR,
2446 G_IO_ERROR_NOT_SUPPORTED,
2447 _("Filesystem does not support symbolic links"));
2449 g_set_io_error (error,
2450 _("Error making symbolic link %s: %s"),
2459 g_local_file_move (GFile *source,
2461 GFileCopyFlags flags,
2462 GCancellable *cancellable,
2463 GFileProgressCallback progress_callback,
2464 gpointer progress_callback_data,
2467 GLocalFile *local_source, *local_destination;
2469 gboolean destination_exist, source_is_dir;
2476 if (!G_IS_LOCAL_FILE (source) ||
2477 !G_IS_LOCAL_FILE (destination))
2479 /* Fall back to default move */
2480 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2484 local_source = G_LOCAL_FILE (source);
2485 local_destination = G_LOCAL_FILE (destination);
2487 res = g_lstat (local_source->filename, &statbuf);
2492 g_set_io_error (error,
2493 _("Error moving file %s: %s"),
2498 source_is_dir = S_ISDIR (statbuf.st_mode);
2499 source_size = statbuf.st_size;
2501 destination_exist = FALSE;
2502 res = g_lstat (local_destination->filename, &statbuf);
2505 destination_exist = TRUE; /* Target file exists */
2507 if (flags & G_FILE_COPY_OVERWRITE)
2509 /* Always fail on dirs, even with overwrite */
2510 if (S_ISDIR (statbuf.st_mode))
2513 g_set_error_literal (error,
2515 G_IO_ERROR_WOULD_MERGE,
2516 _("Can’t move directory over directory"));
2518 g_set_error_literal (error,
2520 G_IO_ERROR_IS_DIRECTORY,
2521 _("Can’t copy over directory"));
2527 g_set_io_error (error,
2528 _("Error moving file %s: %s"),
2534 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2536 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2537 if (g_rename (local_destination->filename, backup_name) == -1)
2539 g_set_error_literal (error,
2541 G_IO_ERROR_CANT_CREATE_BACKUP,
2542 _("Backup file creation failed"));
2543 g_free (backup_name);
2546 g_free (backup_name);
2547 destination_exist = FALSE; /* It did, but no more */
2550 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2552 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2553 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2554 res = g_unlink (local_destination->filename);
2559 g_set_error (error, G_IO_ERROR,
2560 g_io_error_from_errno (errsv),
2561 _("Error removing target file: %s"),
2562 g_strerror (errsv));
2567 if (g_rename (local_source->filename, local_destination->filename) == -1)
2572 /* This will cause the fallback code to run */
2573 g_set_error_literal (error, G_IO_ERROR,
2574 G_IO_ERROR_NOT_SUPPORTED,
2575 _("Move between mounts not supported"));
2576 else if (errsv == EINVAL)
2577 /* This must be an invalid filename, on e.g. FAT, or
2578 we're trying to move the file into itself...
2579 We return invalid filename for both... */
2580 g_set_error_literal (error, G_IO_ERROR,
2581 G_IO_ERROR_INVALID_FILENAME,
2582 _("Invalid filename"));
2584 g_set_io_error (error,
2585 _("Error moving file %s: %s"),
2590 vfs = g_vfs_get_default ();
2591 class = G_VFS_GET_CLASS (vfs);
2592 if (class->local_file_moved)
2593 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2595 /* Make sure we send full copied size */
2596 if (progress_callback)
2597 progress_callback (source_size, source_size, progress_callback_data);
2605 g_local_file_is_nfs_home (const gchar *filename)
2613 is_remote_fs_type (const gchar *fsname)
2617 if (strcmp (fsname, "nfs") == 0)
2619 if (strcmp (fsname, "nfs4") == 0)
2621 if (strcmp (fsname, "cifs") == 0)
2623 if (strcmp (fsname, "smb") == 0)
2625 if (strcmp (fsname, "smb2") == 0)
2627 if (strcmp (fsname, "fuse.sshfs") == 0)
2635 g_local_file_is_nfs_home (const gchar *filename)
2637 static gboolean remote_home = FALSE;
2638 static gsize initialized;
2641 home = g_get_home_dir ();
2642 if (path_has_prefix (filename, home))
2644 if (g_once_init_enter (&initialized))
2648 const gchar *fs_type = NULL;
2650 file = _g_local_file_new (home);
2651 info = g_local_file_query_filesystem_info (file, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, NULL, NULL);
2653 fs_type = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE);
2654 if (g_strcmp0 (fs_type, "nfs") == 0 || g_strcmp0 (fs_type, "nfs4") == 0)
2656 g_clear_object (&info);
2657 g_object_unref (file);
2659 g_once_init_leave (&initialized, TRUE);
2666 #endif /* !G_OS_WIN32 */
2668 static GFileMonitor*
2669 g_local_file_monitor_dir (GFile *file,
2670 GFileMonitorFlags flags,
2671 GCancellable *cancellable,
2674 GLocalFile *local_file = G_LOCAL_FILE (file);
2676 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2679 static GFileMonitor*
2680 g_local_file_monitor_file (GFile *file,
2681 GFileMonitorFlags flags,
2682 GCancellable *cancellable,
2685 GLocalFile *local_file = G_LOCAL_FILE (file);
2687 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2690 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2692 * If available, we use fopenat() in preference to filenames for
2693 * efficiency and safety reasons. We know that fopenat() is available
2694 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2695 * defined as a macro.
2697 * We use a linked list of stack-allocated GSList nodes in order to be
2698 * able to reconstruct the filename for error messages. We actually
2699 * pass the filename to operate on through the top node of the list.
2701 * In case we're using openat(), this top filename will be a basename
2702 * which should be opened in the directory which has also had its fd
2703 * passed along. If we're not using openat() then it will be a full
2704 * absolute filename.
2708 g_local_file_measure_size_error (GFileMeasureFlags flags,
2713 /* Only report an error if we were at the toplevel or if the caller
2714 * requested reporting of all errors.
2716 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2721 /* Skip some work if there is no error return */
2726 /* If using openat() we need to rebuild the filename for the message */
2727 filename = g_string_new (name->data);
2728 for (node = name->next; node; node = node->next)
2732 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2733 utf8 = g_filename_display_name (node->data);
2734 g_string_prepend (filename, utf8);
2741 /* Otherwise, we already have it, so just use it. */
2743 filename = g_string_new (NULL);
2744 utf8 = g_filename_display_name (node->data);
2745 g_string_append (filename, utf8);
2750 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2751 _("Could not determine the disk usage of %s: %s"),
2752 filename->str, g_strerror (saved_errno));
2754 g_string_free (filename, TRUE);
2760 /* We're not reporting this error... */
2766 GFileMeasureFlags flags;
2768 GCancellable *cancellable;
2770 GFileMeasureProgressCallback progress_callback;
2771 gpointer progress_data;
2777 guint64 last_progress_report;
2781 g_local_file_measure_size_of_contents (gint fd,
2783 MeasureState *state,
2787 * _g_stat_is_size_usable:
2788 * @buf: a #GLocalFileStat.
2790 * Checks if the file type is such that the `st_size` field of `struct stat` is
2791 * well-defined by POSIX.
2792 * (see https://pubs.opengroup.org/onlinepubs/009696799/basedefs/sys/stat.h.html)
2794 * This behaviour is aligned with `du` from GNU Coreutils 9.2+
2795 * (see https://lists.gnu.org/archive/html/bug-coreutils/2023-03/msg00007.html)
2796 * and makes apparent size sums well-defined; formerly, they depended on the
2797 * implementation, and could differ across filesystems.
2799 * Returns: %TRUE if the size field is well-defined, %FALSE otherwise.
2801 inline static gboolean
2802 _g_stat_is_size_usable (const GLocalFileStat *buf)
2805 /* Memory objects are defined by POSIX, but are not supported by statx nor Windows */
2807 if (S_TYPEISSHM (buf))
2811 if (S_TYPEISTMO (buf))
2816 return S_ISREG (_g_stat_mode (buf)) || S_ISLNK (_g_stat_mode (buf));
2820 g_local_file_measure_size_of_file (gint parent_fd,
2822 MeasureState *state,
2827 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2830 #if defined (AT_FDCWD)
2831 if (g_local_file_fstatat (parent_fd, name->data, AT_SYMLINK_NOFOLLOW,
2832 G_LOCAL_FILE_STAT_FIELD_BASIC_STATS,
2833 G_LOCAL_FILE_STAT_FIELD_ALL & (~G_LOCAL_FILE_STAT_FIELD_ATIME),
2837 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2839 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2840 if (g_lstat (name->data, &buf) != 0)
2843 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2845 #else /* !AT_FDCWD && !HAVE_LSTAT && G_OS_WIN32 */
2846 if (GLIB_PRIVATE_CALL (g_win32_lstat_utf8) (name->data, &buf) != 0)
2849 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2855 /* If not at the toplevel, check for a device boundary. */
2857 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2858 if (state->contained_on != _g_stat_dev (&buf))
2863 /* If, however, this is the toplevel, set the device number so
2864 * that recursive invocations can compare against it.
2866 state->contained_on = _g_stat_dev (&buf);
2869 #if defined (G_OS_WIN32)
2870 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2871 state->disk_usage += buf.allocated_size;
2873 #elif defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2874 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2875 state->disk_usage += _g_stat_blocks (&buf) * G_GUINT64_CONSTANT (512);
2878 if (_g_stat_is_size_usable (&buf))
2879 state->disk_usage += _g_stat_size (&buf);
2881 if (S_ISDIR (_g_stat_mode (&buf)))
2886 if (state->progress_callback)
2888 /* We could attempt to do some cleverness here in order to avoid
2889 * calling clock_gettime() so much, but we're doing stats and opens
2890 * all over the place already...
2892 if (state->last_progress_report)
2896 now = g_get_monotonic_time ();
2898 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2900 (* state->progress_callback) (TRUE,
2901 state->disk_usage, state->num_dirs, state->num_files,
2902 state->progress_data);
2903 state->last_progress_report = now;
2908 /* We must do an initial report to inform that more reports
2911 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2912 state->last_progress_report = g_get_monotonic_time ();
2916 if (S_ISDIR (_g_stat_mode (&buf)))
2923 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2927 #ifdef HAVE_OPEN_O_DIRECTORY
2928 dir_fd = openat (parent_fd, name->data, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
2930 dir_fd = openat (parent_fd, name->data, O_RDONLY | O_CLOEXEC);
2934 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2937 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2945 g_local_file_measure_size_of_contents (gint fd,
2947 MeasureState *state,
2950 gboolean success = TRUE;
2957 /* If this fails, we want to preserve the errno from fdopendir() */
2959 dirp = fdopendir (fd);
2960 saved_errno = errno;
2961 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2962 g_assert ((dirp == NULL) == (dir == NULL));
2965 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2966 saved_errno = errno;
2975 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2978 while (success && (name = g_dir_read_name (dir)))
2982 node.next = dir_name;
2984 node.data = (gchar *) name;
2986 node.data = g_build_filename (dir_name->data, name, NULL);
2989 success = g_local_file_measure_size_of_file (fd, &node, state, error);
3002 g_local_file_measure_disk_usage (GFile *file,
3003 GFileMeasureFlags flags,
3004 GCancellable *cancellable,
3005 GFileMeasureProgressCallback progress_callback,
3006 gpointer progress_data,
3007 guint64 *disk_usage,
3012 GLocalFile *local_file = G_LOCAL_FILE (file);
3013 MeasureState state = { 0, };
3017 state.flags = flags;
3018 state.cancellable = cancellable;
3019 state.progress_callback = progress_callback;
3020 state.progress_data = progress_data;
3026 node.data = local_file->filename;
3029 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
3033 *disk_usage = state.disk_usage;
3036 *num_dirs = state.num_dirs;
3039 *num_files = state.num_files;
3045 g_local_file_file_iface_init (GFileIface *iface)
3047 iface->dup = g_local_file_dup;
3048 iface->hash = g_local_file_hash;
3049 iface->equal = g_local_file_equal;
3050 iface->is_native = g_local_file_is_native;
3051 iface->has_uri_scheme = g_local_file_has_uri_scheme;
3052 iface->get_uri_scheme = g_local_file_get_uri_scheme;
3053 iface->get_basename = g_local_file_get_basename;
3054 iface->get_path = g_local_file_get_path;
3055 iface->get_uri = g_local_file_get_uri;
3056 iface->get_parse_name = g_local_file_get_parse_name;
3057 iface->get_parent = g_local_file_get_parent;
3058 iface->prefix_matches = g_local_file_prefix_matches;
3059 iface->get_relative_path = g_local_file_get_relative_path;
3060 iface->resolve_relative_path = g_local_file_resolve_relative_path;
3061 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
3062 iface->set_display_name = g_local_file_set_display_name;
3063 iface->enumerate_children = g_local_file_enumerate_children;
3064 iface->query_info = g_local_file_query_info;
3065 iface->query_filesystem_info = g_local_file_query_filesystem_info;
3066 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
3067 iface->query_settable_attributes = g_local_file_query_settable_attributes;
3068 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
3069 iface->set_attribute = g_local_file_set_attribute;
3070 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
3071 iface->read_fn = g_local_file_read;
3072 iface->append_to = g_local_file_append_to;
3073 iface->create = g_local_file_create;
3074 iface->replace = g_local_file_replace;
3075 iface->open_readwrite = g_local_file_open_readwrite;
3076 iface->create_readwrite = g_local_file_create_readwrite;
3077 iface->replace_readwrite = g_local_file_replace_readwrite;
3078 iface->delete_file = g_local_file_delete;
3079 iface->trash = g_local_file_trash;
3080 iface->make_directory = g_local_file_make_directory;
3082 iface->make_symbolic_link = g_local_file_make_symbolic_link;
3084 iface->move = g_local_file_move;
3085 iface->monitor_dir = g_local_file_monitor_dir;
3086 iface->monitor_file = g_local_file_monitor_file;
3087 iface->measure_disk_usage = g_local_file_measure_disk_usage;
3089 iface->supports_thread_contexts = TRUE;