Merge branch 'mingw-statbuf-size' into 'master'
[glib.git] / gio / glocalfile.c
blob30fa2281ca742c573200cdf434e47e52591a1773
1 /* GIO - GLib Input, Output and Streaming Library
2 *
3 * Copyright (C) 2006-2007 Red Hat, Inc.
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.
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.
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/>.
18 * Author: Alexander Larsson <alexl@redhat.com>
21 #include "config.h"
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
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
48 #ifndef O_BINARY
49 #define O_BINARY 0
50 #endif
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 #endif
71 #include "glib-private.h"
73 #ifdef G_OS_WIN32
74 #include <windows.h>
75 #include <io.h>
76 #include <direct.h>
78 #ifndef FILE_READ_ONLY_VOLUME
79 #define FILE_READ_ONLY_VOLUME 0x00080000
80 #endif
82 #ifndef S_ISDIR
83 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
84 #endif
85 #ifndef S_ISLNK
86 #define S_ISLNK(m) (0)
87 #endif
89 #ifndef ECANCELED
90 #define ECANCELED 105
91 #endif
92 #endif
95 static void g_local_file_file_iface_init (GFileIface *iface);
97 static GFileAttributeInfoList *local_writable_attributes = NULL;
98 static /* GFileAttributeInfoList * */ gsize local_writable_namespaces = 0;
100 struct _GLocalFile
102 GObject parent_instance;
104 char *filename;
107 #define g_local_file_get_type _g_local_file_get_type
108 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
109 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
110 g_local_file_file_iface_init))
112 static char *find_mountpoint_for (const char *file, dev_t dev);
114 static void
115 g_local_file_finalize (GObject *object)
117 GLocalFile *local;
119 local = G_LOCAL_FILE (object);
121 g_free (local->filename);
123 G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
126 static void
127 g_local_file_class_init (GLocalFileClass *klass)
129 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
130 GFileAttributeInfoList *list;
132 gobject_class->finalize = g_local_file_finalize;
134 /* Set up attribute lists */
136 /* Writable attributes: */
138 list = g_file_attribute_info_list_new ();
140 g_file_attribute_info_list_add (list,
141 G_FILE_ATTRIBUTE_UNIX_MODE,
142 G_FILE_ATTRIBUTE_TYPE_UINT32,
143 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
144 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
146 #ifdef G_OS_UNIX
147 g_file_attribute_info_list_add (list,
148 G_FILE_ATTRIBUTE_UNIX_UID,
149 G_FILE_ATTRIBUTE_TYPE_UINT32,
150 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
151 g_file_attribute_info_list_add (list,
152 G_FILE_ATTRIBUTE_UNIX_GID,
153 G_FILE_ATTRIBUTE_TYPE_UINT32,
154 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
155 #endif
157 #ifdef HAVE_SYMLINK
158 g_file_attribute_info_list_add (list,
159 G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
160 G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
162 #endif
164 #ifdef HAVE_UTIMES
165 g_file_attribute_info_list_add (list,
166 G_FILE_ATTRIBUTE_TIME_MODIFIED,
167 G_FILE_ATTRIBUTE_TYPE_UINT64,
168 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
169 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
170 g_file_attribute_info_list_add (list,
171 G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
172 G_FILE_ATTRIBUTE_TYPE_UINT32,
173 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
174 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
175 /* When copying, the target file is accessed. Replicating
176 * the source access time does not make sense in this case.
178 g_file_attribute_info_list_add (list,
179 G_FILE_ATTRIBUTE_TIME_ACCESS,
180 G_FILE_ATTRIBUTE_TYPE_UINT64,
181 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
182 g_file_attribute_info_list_add (list,
183 G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
184 G_FILE_ATTRIBUTE_TYPE_UINT32,
185 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
186 #endif
188 local_writable_attributes = list;
191 static void
192 g_local_file_init (GLocalFile *local)
196 const char *
197 _g_local_file_get_filename (GLocalFile *file)
199 return file->filename;
202 GFile *
203 _g_local_file_new (const char *filename)
205 GLocalFile *local;
207 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
208 local->filename = g_canonicalize_filename (filename, NULL);
210 return G_FILE (local);
213 /*< internal >
214 * g_local_file_new_from_dirname_and_basename:
215 * @dirname: an absolute, canonical directory name
216 * @basename: the name of a child inside @dirname
218 * Creates a #GFile from @dirname and @basename.
220 * This is more efficient than pasting the fields together for yourself
221 * and creating a #GFile from the result, and also more efficient than
222 * creating a #GFile for the dirname and using g_file_get_child().
224 * @dirname must be canonical, as per GLocalFile's opinion of what
225 * canonical means. This means that you should only pass strings that
226 * were returned by _g_local_file_get_filename().
228 * Returns: a #GFile
230 GFile *
231 g_local_file_new_from_dirname_and_basename (const gchar *dirname,
232 const gchar *basename)
234 GLocalFile *local;
236 g_return_val_if_fail (dirname != NULL, NULL);
237 g_return_val_if_fail (basename && basename[0] && !strchr (basename, '/'), NULL);
239 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
240 local->filename = g_build_filename (dirname, basename, NULL);
242 return G_FILE (local);
245 static gboolean
246 g_local_file_is_native (GFile *file)
248 return TRUE;
251 static gboolean
252 g_local_file_has_uri_scheme (GFile *file,
253 const char *uri_scheme)
255 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
258 static char *
259 g_local_file_get_uri_scheme (GFile *file)
261 return g_strdup ("file");
264 static char *
265 g_local_file_get_basename (GFile *file)
267 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
270 static char *
271 g_local_file_get_path (GFile *file)
273 return g_strdup (G_LOCAL_FILE (file)->filename);
276 static char *
277 g_local_file_get_uri (GFile *file)
279 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
282 static gboolean
283 get_filename_charset (const gchar **filename_charset)
285 const gchar **charsets;
286 gboolean is_utf8;
288 is_utf8 = g_get_filename_charsets (&charsets);
290 if (filename_charset)
291 *filename_charset = charsets[0];
293 return is_utf8;
296 static gboolean
297 name_is_valid_for_display (const char *string,
298 gboolean is_valid_utf8)
300 char c;
302 if (!is_valid_utf8 &&
303 !g_utf8_validate (string, -1, NULL))
304 return FALSE;
306 while ((c = *string++) != 0)
308 if (g_ascii_iscntrl (c))
309 return FALSE;
312 return TRUE;
315 static char *
316 g_local_file_get_parse_name (GFile *file)
318 const char *filename;
319 char *parse_name;
320 const gchar *charset;
321 char *utf8_filename;
322 char *roundtripped_filename;
323 gboolean free_utf8_filename;
324 gboolean is_valid_utf8;
325 char *escaped_path;
327 filename = G_LOCAL_FILE (file)->filename;
328 if (get_filename_charset (&charset))
330 utf8_filename = (char *)filename;
331 free_utf8_filename = FALSE;
332 is_valid_utf8 = FALSE; /* Can't guarantee this */
334 else
336 utf8_filename = g_convert (filename, -1,
337 "UTF-8", charset, NULL, NULL, NULL);
338 free_utf8_filename = TRUE;
339 is_valid_utf8 = TRUE;
341 if (utf8_filename != NULL)
343 /* Make sure we can roundtrip: */
344 roundtripped_filename = g_convert (utf8_filename, -1,
345 charset, "UTF-8", NULL, NULL, NULL);
347 if (roundtripped_filename == NULL ||
348 strcmp (filename, roundtripped_filename) != 0)
350 g_free (utf8_filename);
351 utf8_filename = NULL;
354 g_free (roundtripped_filename);
358 if (utf8_filename != NULL &&
359 name_is_valid_for_display (utf8_filename, is_valid_utf8))
361 if (free_utf8_filename)
362 parse_name = utf8_filename;
363 else
364 parse_name = g_strdup (utf8_filename);
366 else
368 #ifdef G_OS_WIN32
369 char *dup_filename, *p, *backslash;
371 /* Turn backslashes into forward slashes like
372 * g_filename_to_uri() would do (but we can't use that because
373 * it doesn't output IRIs).
375 dup_filename = g_strdup (filename);
376 filename = p = dup_filename;
378 while ((backslash = strchr (p, '\\')) != NULL)
380 *backslash = '/';
381 p = backslash + 1;
383 #endif
385 escaped_path = g_uri_escape_string (filename,
386 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
387 TRUE);
388 parse_name = g_strconcat ("file://",
389 (*escaped_path != '/') ? "/" : "",
390 escaped_path,
391 NULL);
393 g_free (escaped_path);
394 #ifdef G_OS_WIN32
395 g_free (dup_filename);
396 #endif
397 if (free_utf8_filename)
398 g_free (utf8_filename);
401 return parse_name;
404 static GFile *
405 g_local_file_get_parent (GFile *file)
407 GLocalFile *local = G_LOCAL_FILE (file);
408 const char *non_root;
409 char *dirname;
410 GFile *parent;
412 /* Check for root; local->filename is guaranteed to be absolute, so
413 * g_path_skip_root() should never return NULL. */
414 non_root = g_path_skip_root (local->filename);
415 g_assert (non_root != NULL);
417 if (*non_root == 0)
418 return NULL;
420 dirname = g_path_get_dirname (local->filename);
421 parent = _g_local_file_new (dirname);
422 g_free (dirname);
423 return parent;
426 static GFile *
427 g_local_file_dup (GFile *file)
429 GLocalFile *local = G_LOCAL_FILE (file);
431 return _g_local_file_new (local->filename);
434 static guint
435 g_local_file_hash (GFile *file)
437 GLocalFile *local = G_LOCAL_FILE (file);
439 return g_str_hash (local->filename);
442 static gboolean
443 g_local_file_equal (GFile *file1,
444 GFile *file2)
446 GLocalFile *local1 = G_LOCAL_FILE (file1);
447 GLocalFile *local2 = G_LOCAL_FILE (file2);
449 return g_str_equal (local1->filename, local2->filename);
452 static const char *
453 match_prefix (const char *path,
454 const char *prefix)
456 int prefix_len;
458 prefix_len = strlen (prefix);
459 if (strncmp (path, prefix, prefix_len) != 0)
460 return NULL;
462 /* Handle the case where prefix is the root, so that
463 * the IS_DIR_SEPRARATOR check below works */
464 if (prefix_len > 0 &&
465 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
466 prefix_len--;
468 return path + prefix_len;
471 static gboolean
472 g_local_file_prefix_matches (GFile *parent,
473 GFile *descendant)
475 GLocalFile *parent_local = G_LOCAL_FILE (parent);
476 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
477 const char *remainder;
479 remainder = match_prefix (descendant_local->filename, parent_local->filename);
480 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
481 return TRUE;
482 return FALSE;
485 static char *
486 g_local_file_get_relative_path (GFile *parent,
487 GFile *descendant)
489 GLocalFile *parent_local = G_LOCAL_FILE (parent);
490 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
491 const char *remainder;
493 remainder = match_prefix (descendant_local->filename, parent_local->filename);
495 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
496 return g_strdup (remainder + 1);
497 return NULL;
500 static GFile *
501 g_local_file_resolve_relative_path (GFile *file,
502 const char *relative_path)
504 GLocalFile *local = G_LOCAL_FILE (file);
505 char *filename;
506 GFile *child;
508 if (g_path_is_absolute (relative_path))
509 return _g_local_file_new (relative_path);
511 filename = g_build_filename (local->filename, relative_path, NULL);
512 child = _g_local_file_new (filename);
513 g_free (filename);
515 return child;
518 static GFileEnumerator *
519 g_local_file_enumerate_children (GFile *file,
520 const char *attributes,
521 GFileQueryInfoFlags flags,
522 GCancellable *cancellable,
523 GError **error)
525 GLocalFile *local = G_LOCAL_FILE (file);
526 return _g_local_file_enumerator_new (local,
527 attributes, flags,
528 cancellable, error);
531 static GFile *
532 g_local_file_get_child_for_display_name (GFile *file,
533 const char *display_name,
534 GError **error)
536 GFile *new_file;
537 char *basename;
539 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
540 if (basename == NULL)
542 g_set_error (error, G_IO_ERROR,
543 G_IO_ERROR_INVALID_FILENAME,
544 _("Invalid filename %s"), display_name);
545 return NULL;
548 new_file = g_file_get_child (file, basename);
549 g_free (basename);
551 return new_file;
554 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
555 static const char *
556 get_fs_type (long f_type)
558 /* filesystem ids taken from linux manpage */
559 switch (f_type)
561 case 0xadf5:
562 return "adfs";
563 case 0x5346414f:
564 return "afs";
565 case 0x0187:
566 return "autofs";
567 case 0xADFF:
568 return "affs";
569 case 0x62646576:
570 return "bdevfs";
571 case 0x42465331:
572 return "befs";
573 case 0x1BADFACE:
574 return "bfs";
575 case 0x42494e4d:
576 return "binfmt_misc";
577 case 0x9123683E:
578 return "btrfs";
579 case 0x73727279:
580 return "btrfs_test_fs";
581 case 0x27e0eb:
582 return "cgroup";
583 case 0x63677270:
584 return "cgroup2";
585 case 0xFF534D42:
586 return "cifs";
587 case 0x73757245:
588 return "coda";
589 case 0x012FF7B7:
590 return "coh";
591 case 0x62656570:
592 return "configfs";
593 case 0x28cd3d45:
594 return "cramfs";
595 case 0x64626720:
596 return "debugfs";
597 case 0x1373:
598 return "devfs";
599 case 0x1cd1:
600 return "devpts";
601 case 0xf15f:
602 return "ecryptfs";
603 case 0xde5e81e4:
604 return "efivarfs";
605 case 0x00414A53:
606 return "efs";
607 case 0x137D:
608 return "ext";
609 case 0xEF51:
610 return "ext2";
611 case 0xEF53:
612 return "ext3/ext4";
613 case 0xF2F52010:
614 return "f2fs";
615 case 0x65735546:
616 return "fuse";
617 case 0x65735543:
618 return "fusectl";
619 case 0xBAD1DEA:
620 return "futexfs";
621 case 0x4244:
622 return "hfs";
623 case 0x00c0ffee:
624 return "hostfs";
625 case 0xF995E849:
626 return "hpfs";
627 case 0x958458f6:
628 return "hugetlbfs";
629 case 0x9660:
630 return "isofs";
631 case 0x72b6:
632 return "jffs2";
633 case 0x3153464a:
634 return "jfs";
635 case 0x137F:
636 return "minix";
637 case 0x138F:
638 return "minix2";
639 case 0x2468:
640 return "minix2";
641 case 0x2478:
642 return "minix22";
643 case 0x4d5a:
644 return "minix3";
645 case 0x19800202:
646 return "mqueue";
647 case 0x4d44:
648 return "msdos";
649 case 0x564c:
650 return "ncp";
651 case 0x6969:
652 return "nfs";
653 case 0x3434:
654 return "nilfs";
655 case 0x6e736673:
656 return "nsfs";
657 case 0x5346544e:
658 return "ntfs";
659 case 0x7461636f:
660 return "ocfs2";
661 case 0x9fa1:
662 return "openprom";
663 case 0x794c7630:
664 return "overlay";
665 case 0x50495045:
666 return "pipefs";
667 case 0x9fa0:
668 return "proc";
669 case 0x6165676C:
670 return "pstore";
671 case 0x002f:
672 return "qnx4";
673 case 0x68191122:
674 return "qnx6";
675 case 0x858458f6:
676 return "ramfs";
677 case 0x52654973:
678 return "reiserfs";
679 case 0x7275:
680 return "romfs";
681 case 0x67596969:
682 return "rpc_pipefs";
683 case 0x73636673:
684 return "securityfs";
685 case 0xf97cff8c:
686 return "selinuxfs";
687 case 0x43415d53:
688 return "smackfs";
689 case 0x517B:
690 return "smb";
691 case 0x534F434B:
692 return "sockfs";
693 case 0x73717368:
694 return "squashfs";
695 case 0x62656572:
696 return "sysfs";
697 case 0x012FF7B6:
698 return "sysv2";
699 case 0x012FF7B5:
700 return "sysv4";
701 case 0x01021994:
702 return "tmpfs";
703 case 0x74726163:
704 return "tracefs";
705 case 0x15013346:
706 return "udf";
707 case 0x00011954:
708 return "ufs";
709 case 0x9fa2:
710 return "usbdevice";
711 case 0x01021997:
712 return "v9fs";
713 case 0xa501FCF5:
714 return "vxfs";
715 case 0xabba1974:
716 return "xenfs";
717 case 0x012FF7B4:
718 return "xenix";
719 case 0x58465342:
720 return "xfs";
721 case 0x012FD16D:
722 return "xiafs";
723 case 0x52345362:
724 return "reiser4";
725 default:
726 return NULL;
729 #endif
731 #ifndef G_OS_WIN32
733 G_LOCK_DEFINE_STATIC(mount_info_hash);
734 static GHashTable *mount_info_hash = NULL;
735 static guint64 mount_info_hash_cache_time = 0;
737 typedef enum {
738 MOUNT_INFO_READONLY = 1<<0
739 } MountInfo;
741 static gboolean
742 device_equal (gconstpointer v1,
743 gconstpointer v2)
745 return *(dev_t *)v1 == *(dev_t *)v2;
748 static guint
749 device_hash (gconstpointer v)
751 return (guint) *(dev_t *)v;
754 static void
755 get_mount_info (GFileInfo *fs_info,
756 const char *path,
757 GFileAttributeMatcher *matcher)
759 GStatBuf buf;
760 gboolean got_info;
761 gpointer info_as_ptr;
762 guint mount_info;
763 char *mountpoint;
764 dev_t *dev;
765 GUnixMountEntry *mount;
766 guint64 cache_time;
768 if (g_lstat (path, &buf) != 0)
769 return;
771 G_LOCK (mount_info_hash);
773 if (mount_info_hash == NULL)
774 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
775 g_free, NULL);
778 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
779 g_hash_table_remove_all (mount_info_hash);
781 got_info = g_hash_table_lookup_extended (mount_info_hash,
782 &buf.st_dev,
783 NULL,
784 &info_as_ptr);
786 G_UNLOCK (mount_info_hash);
788 mount_info = GPOINTER_TO_UINT (info_as_ptr);
790 if (!got_info)
792 mount_info = 0;
794 mountpoint = find_mountpoint_for (path, buf.st_dev);
795 if (mountpoint == NULL)
796 mountpoint = g_strdup ("/");
798 mount = g_unix_mount_at (mountpoint, &cache_time);
799 if (mount)
801 if (g_unix_mount_is_readonly (mount))
802 mount_info |= MOUNT_INFO_READONLY;
804 g_unix_mount_free (mount);
807 g_free (mountpoint);
809 dev = g_new0 (dev_t, 1);
810 *dev = buf.st_dev;
812 G_LOCK (mount_info_hash);
813 mount_info_hash_cache_time = cache_time;
814 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
815 G_UNLOCK (mount_info_hash);
818 if (mount_info & MOUNT_INFO_READONLY)
819 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
822 #endif
824 #ifdef G_OS_WIN32
826 static gboolean
827 is_xp_or_later (void)
829 static int result = -1;
831 if (result == -1)
833 #ifndef _MSC_VER
834 OSVERSIONINFOEX ver_info = {0};
835 DWORDLONG cond_mask = 0;
836 int op = VER_GREATER_EQUAL;
838 ver_info.dwOSVersionInfoSize = sizeof ver_info;
839 ver_info.dwMajorVersion = 5;
840 ver_info.dwMinorVersion = 1;
842 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
843 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
845 result = VerifyVersionInfo (&ver_info,
846 VER_MAJORVERSION | VER_MINORVERSION,
847 cond_mask) != 0;
848 #else
849 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
850 #endif
853 return result;
856 static wchar_t *
857 get_volume_for_path (const char *path)
859 long len;
860 wchar_t *wpath;
861 wchar_t *result;
863 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
864 result = g_new (wchar_t, MAX_PATH);
866 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
868 char *msg = g_win32_error_message (GetLastError ());
869 g_critical ("GetVolumePathName failed: %s", msg);
870 g_free (msg);
871 g_free (result);
872 g_free (wpath);
873 return NULL;
876 len = wcslen (result);
877 if (len > 0 && result[len-1] != L'\\')
879 result = g_renew (wchar_t, result, len + 2);
880 result[len] = L'\\';
881 result[len + 1] = 0;
884 g_free (wpath);
885 return result;
888 static char *
889 find_mountpoint_for (const char *file, dev_t dev)
891 wchar_t *wpath;
892 char *utf8_path;
894 wpath = get_volume_for_path (file);
895 if (!wpath)
896 return NULL;
898 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
900 g_free (wpath);
901 return utf8_path;
904 static void
905 get_filesystem_readonly (GFileInfo *info,
906 const char *path)
908 wchar_t *rootdir;
910 rootdir = get_volume_for_path (path);
912 if (rootdir)
914 if (is_xp_or_later ())
916 DWORD flags;
917 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
918 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
919 (flags & FILE_READ_ONLY_VOLUME) != 0);
921 else
923 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
924 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
928 g_free (rootdir);
931 #endif /* G_OS_WIN32 */
933 #pragma GCC diagnostic push
934 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
935 static void
936 g_set_io_error (GError **error,
937 const gchar *msg,
938 GFile *file,
939 gint errsv)
941 GLocalFile *local = G_LOCAL_FILE (file);
942 gchar *display_name;
944 display_name = g_filename_display_name (local->filename);
945 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
946 msg, display_name, g_strerror (errsv));
947 g_free (display_name);
949 #pragma GCC diagnostic pop
951 static GFileInfo *
952 g_local_file_query_filesystem_info (GFile *file,
953 const char *attributes,
954 GCancellable *cancellable,
955 GError **error)
957 GLocalFile *local = G_LOCAL_FILE (file);
958 GFileInfo *info;
959 int statfs_result = 0;
960 gboolean no_size;
961 #ifndef G_OS_WIN32
962 const char *fstype;
963 #ifdef USE_STATFS
964 guint64 block_size;
965 struct statfs statfs_buffer;
966 #elif defined(USE_STATVFS)
967 guint64 block_size;
968 struct statvfs statfs_buffer;
969 #endif /* USE_STATFS */
970 #endif /* G_OS_WIN32 */
971 GFileAttributeMatcher *attribute_matcher;
973 no_size = FALSE;
975 #ifdef USE_STATFS
977 #if STATFS_ARGS == 2
978 statfs_result = statfs (local->filename, &statfs_buffer);
979 #elif STATFS_ARGS == 4
980 statfs_result = statfs (local->filename, &statfs_buffer,
981 sizeof (statfs_buffer), 0);
982 #endif /* STATFS_ARGS == 2 */
983 block_size = statfs_buffer.f_bsize;
985 /* Many backends can't report free size (for instance the gvfs fuse
986 * backend for backend not supporting this), and set f_bfree to 0,
987 * but it can be 0 for real too. We treat the available == 0 and
988 * free == 0 case as "both of these are invalid", but only on file systems
989 * which are known to not support this (otherwise we can omit metadata for
990 * systems which are legitimately full). */
991 #if defined(__linux__)
992 if (statfs_result == 0 &&
993 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
994 (/* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
995 statfs_buffer.f_type == 0x564c ||
996 /* man statfs: FUSE_SUPER_MAGIC == 0x65735546 */
997 statfs_buffer.f_type == 0x65735546))
998 no_size = TRUE;
999 #endif /* __linux__ */
1001 #elif defined(USE_STATVFS)
1002 statfs_result = statvfs (local->filename, &statfs_buffer);
1003 block_size = statfs_buffer.f_frsize;
1004 #endif /* USE_STATFS */
1006 if (statfs_result == -1)
1008 int errsv = errno;
1010 g_set_io_error (error,
1011 _("Error getting filesystem info for %s: %s"),
1012 file, errsv);
1013 return NULL;
1016 info = g_file_info_new ();
1018 attribute_matcher = g_file_attribute_matcher_new (attributes);
1020 if (!no_size &&
1021 g_file_attribute_matcher_matches (attribute_matcher,
1022 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1024 #ifdef G_OS_WIN32
1025 gchar *localdir = g_path_get_dirname (local->filename);
1026 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1027 ULARGE_INTEGER li;
1029 g_free (localdir);
1030 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1031 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1032 g_free (wdirname);
1033 #else
1034 #if defined(USE_STATFS) || defined(USE_STATVFS)
1035 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1036 #endif
1037 #endif
1039 if (!no_size &&
1040 g_file_attribute_matcher_matches (attribute_matcher,
1041 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1043 #ifdef G_OS_WIN32
1044 gchar *localdir = g_path_get_dirname (local->filename);
1045 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1046 ULARGE_INTEGER li;
1048 g_free (localdir);
1049 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1050 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1051 g_free (wdirname);
1052 #else
1053 #if defined(USE_STATFS) || defined(USE_STATVFS)
1054 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1055 #endif
1056 #endif /* G_OS_WIN32 */
1059 if (!no_size &&
1060 g_file_attribute_matcher_matches (attribute_matcher,
1061 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1063 #ifdef G_OS_WIN32
1064 gchar *localdir = g_path_get_dirname (local->filename);
1065 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1066 ULARGE_INTEGER li_free;
1067 ULARGE_INTEGER li_total;
1069 g_free (localdir);
1070 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1071 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1072 g_free (wdirname);
1073 #else
1074 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1075 #endif /* G_OS_WIN32 */
1078 #ifndef G_OS_WIN32
1079 #ifdef USE_STATFS
1080 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1081 fstype = statfs_buffer.f_fstypename;
1082 #else
1083 fstype = get_fs_type (statfs_buffer.f_type);
1084 #endif
1086 #elif defined(USE_STATVFS)
1087 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1088 fstype = statfs_buffer.f_fstypename;
1089 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1090 fstype = statfs_buffer.f_basetype;
1091 #else
1092 fstype = NULL;
1093 #endif
1094 #endif /* USE_STATFS */
1096 if (fstype &&
1097 g_file_attribute_matcher_matches (attribute_matcher,
1098 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1099 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1100 #endif /* G_OS_WIN32 */
1102 if (g_file_attribute_matcher_matches (attribute_matcher,
1103 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1105 #ifdef G_OS_WIN32
1106 get_filesystem_readonly (info, local->filename);
1107 #else
1108 get_mount_info (info, local->filename, attribute_matcher);
1109 #endif /* G_OS_WIN32 */
1112 if (g_file_attribute_matcher_matches (attribute_matcher,
1113 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
1114 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE,
1115 g_local_file_is_remote (local->filename));
1117 g_file_attribute_matcher_unref (attribute_matcher);
1119 return info;
1122 static GMount *
1123 g_local_file_find_enclosing_mount (GFile *file,
1124 GCancellable *cancellable,
1125 GError **error)
1127 GLocalFile *local = G_LOCAL_FILE (file);
1128 GStatBuf buf;
1129 char *mountpoint;
1130 GMount *mount;
1132 if (g_lstat (local->filename, &buf) != 0)
1133 goto error;
1135 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1136 if (mountpoint == NULL)
1137 goto error;
1139 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1140 g_free (mountpoint);
1141 if (mount)
1142 return mount;
1144 error:
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
1148 * exists.
1150 _("Containing mount for file %s not found"),
1151 file, 0);
1153 return NULL;
1156 static GFile *
1157 g_local_file_set_display_name (GFile *file,
1158 const char *display_name,
1159 GCancellable *cancellable,
1160 GError **error)
1162 GLocalFile *local, *new_local;
1163 GFile *new_file, *parent;
1164 GStatBuf statbuf;
1165 GVfsClass *class;
1166 GVfs *vfs;
1167 int errsv;
1169 parent = g_file_get_parent (file);
1170 if (parent == NULL)
1172 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1173 _("Can’t rename root directory"));
1174 return NULL;
1177 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1178 g_object_unref (parent);
1180 if (new_file == NULL)
1181 return NULL;
1182 local = G_LOCAL_FILE (file);
1183 new_local = G_LOCAL_FILE (new_file);
1185 if (g_lstat (new_local->filename, &statbuf) == -1)
1187 errsv = errno;
1189 if (errsv != ENOENT)
1191 g_set_io_error (error, _("Error renaming file %s: %s"), new_file, errsv);
1192 return NULL;
1195 else
1197 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
1198 _("Can’t rename file, filename already exists"));
1199 return NULL;
1202 if (g_rename (local->filename, new_local->filename) == -1)
1204 errsv = errno;
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"));
1212 else
1213 g_set_io_error (error,
1214 _("Error renaming file %s: %s"),
1215 file, errsv);
1216 g_object_unref (new_file);
1217 return NULL;
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);
1225 return new_file;
1228 static GFileInfo *
1229 g_local_file_query_info (GFile *file,
1230 const char *attributes,
1231 GFileQueryInfoFlags flags,
1232 GCancellable *cancellable,
1233 GError **error)
1235 GLocalFile *local = G_LOCAL_FILE (file);
1236 GFileInfo *info;
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);
1247 g_free (dirname);
1249 info = _g_local_file_info_get (basename, local->filename,
1250 matcher, flags, &parent_info,
1251 error);
1254 _g_local_file_info_free_parent_info (&parent_info);
1255 g_free (basename);
1257 g_file_attribute_matcher_unref (matcher);
1259 return info;
1262 static GFileAttributeInfoList *
1263 g_local_file_query_settable_attributes (GFile *file,
1264 GCancellable *cancellable,
1265 GError **error)
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,
1273 GError **error)
1275 GFileAttributeInfoList *list;
1276 GVfsClass *class;
1277 GVfs *vfs;
1279 if (g_once_init_enter (&local_writable_namespaces))
1281 /* Writable namespaces: */
1283 list = g_file_attribute_info_list_new ();
1285 #ifdef HAVE_XATTR
1286 g_file_attribute_info_list_add (list,
1287 "xattr",
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,
1292 "xattr-sys",
1293 G_FILE_ATTRIBUTE_TYPE_STRING,
1294 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1295 #endif
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 (&local_writable_namespaces, (gsize)list);
1304 list = (GFileAttributeInfoList *)local_writable_namespaces;
1306 return g_file_attribute_info_list_ref (list);
1309 static gboolean
1310 g_local_file_set_attribute (GFile *file,
1311 const char *attribute,
1312 GFileAttributeType type,
1313 gpointer value_p,
1314 GFileQueryInfoFlags flags,
1315 GCancellable *cancellable,
1316 GError **error)
1318 GLocalFile *local = G_LOCAL_FILE (file);
1320 return _g_local_file_info_set_attribute (local->filename,
1321 attribute,
1322 type,
1323 value_p,
1324 flags,
1325 cancellable,
1326 error);
1329 static gboolean
1330 g_local_file_set_attributes_from_info (GFile *file,
1331 GFileInfo *info,
1332 GFileQueryInfoFlags flags,
1333 GCancellable *cancellable,
1334 GError **error)
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,
1341 info, flags,
1342 cancellable,
1343 error);
1345 if (!res)
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,
1358 GError **error)
1360 GLocalFile *local = G_LOCAL_FILE (file);
1361 int fd, ret;
1362 GLocalFileStat buf;
1364 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1365 if (fd == -1)
1367 int errsv = errno;
1369 #ifdef G_OS_WIN32
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))
1375 errsv = EISDIR;
1377 #endif
1378 g_set_io_error (error,
1379 _("Error opening file %s: %s"),
1380 file, errsv);
1381 return NULL;
1384 #ifdef G_OS_WIN32
1385 ret = GLIB_PRIVATE_CALL (g_win32_fstat) (fd, &buf);
1386 #else
1387 ret = fstat (fd, &buf);
1388 #endif
1390 if (ret == 0 && S_ISDIR (buf.st_mode))
1392 (void) g_close (fd, NULL);
1393 g_set_io_error (error,
1394 _("Error opening file %s: %s"),
1395 file, EISDIR);
1396 return NULL;
1399 return _g_local_file_input_stream_new (fd);
1402 static GFileOutputStream *
1403 g_local_file_append_to (GFile *file,
1404 GFileCreateFlags flags,
1405 GCancellable *cancellable,
1406 GError **error)
1408 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1409 flags, cancellable, error);
1412 static GFileOutputStream *
1413 g_local_file_create (GFile *file,
1414 GFileCreateFlags flags,
1415 GCancellable *cancellable,
1416 GError **error)
1418 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1419 FALSE, flags, NULL,
1420 cancellable, error);
1423 static GFileOutputStream *
1424 g_local_file_replace (GFile *file,
1425 const char *etag,
1426 gboolean make_backup,
1427 GFileCreateFlags flags,
1428 GCancellable *cancellable,
1429 GError **error)
1431 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1432 FALSE,
1433 etag, make_backup, flags, NULL,
1434 cancellable, error);
1437 static GFileIOStream *
1438 g_local_file_open_readwrite (GFile *file,
1439 GCancellable *cancellable,
1440 GError **error)
1442 GFileOutputStream *output;
1443 GFileIOStream *res;
1445 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1446 TRUE,
1447 cancellable, error);
1448 if (output == NULL)
1449 return NULL;
1451 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1452 g_object_unref (output);
1453 return res;
1456 static GFileIOStream *
1457 g_local_file_create_readwrite (GFile *file,
1458 GFileCreateFlags flags,
1459 GCancellable *cancellable,
1460 GError **error)
1462 GFileOutputStream *output;
1463 GFileIOStream *res;
1465 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1466 TRUE, flags, NULL,
1467 cancellable, error);
1468 if (output == NULL)
1469 return NULL;
1471 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1472 g_object_unref (output);
1473 return res;
1476 static GFileIOStream *
1477 g_local_file_replace_readwrite (GFile *file,
1478 const char *etag,
1479 gboolean make_backup,
1480 GFileCreateFlags flags,
1481 GCancellable *cancellable,
1482 GError **error)
1484 GFileOutputStream *output;
1485 GFileIOStream *res;
1487 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1488 TRUE,
1489 etag, make_backup, flags, NULL,
1490 cancellable, error);
1491 if (output == NULL)
1492 return NULL;
1494 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1495 g_object_unref (output);
1496 return res;
1499 static gboolean
1500 g_local_file_delete (GFile *file,
1501 GCancellable *cancellable,
1502 GError **error)
1504 GLocalFile *local = G_LOCAL_FILE (file);
1505 GVfsClass *class;
1506 GVfs *vfs;
1508 if (g_remove (local->filename) == -1)
1510 int errsv = errno;
1512 /* Posix allows EEXIST too, but the more sane error
1513 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1514 expects */
1515 if (errsv == EEXIST)
1516 errsv = ENOTEMPTY;
1518 g_set_io_error (error,
1519 _("Error removing file %s: %s"),
1520 file, errsv);
1521 return FALSE;
1524 vfs = g_vfs_get_default ();
1525 class = G_VFS_GET_CLASS (vfs);
1526 if (class->local_file_removed)
1527 class->local_file_removed (vfs, local->filename);
1529 return TRUE;
1532 #ifndef G_OS_WIN32
1534 static char *
1535 strip_trailing_slashes (const char *path)
1537 char *path_copy;
1538 int len;
1540 path_copy = g_strdup (path);
1541 len = strlen (path_copy);
1542 while (len > 1 && path_copy[len-1] == '/')
1543 path_copy[--len] = 0;
1545 return path_copy;
1548 static char *
1549 expand_symlink (const char *link)
1551 char *resolved, *canonical, *parent, *link2;
1552 char symlink_value[4096];
1553 #ifdef G_OS_WIN32
1554 #else
1555 gssize res;
1556 #endif
1558 #ifdef G_OS_WIN32
1559 #else
1560 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1562 if (res == -1)
1563 return g_strdup (link);
1564 symlink_value[res] = 0;
1565 #endif
1567 if (g_path_is_absolute (symlink_value))
1568 return g_canonicalize_filename (symlink_value, NULL);
1569 else
1571 link2 = strip_trailing_slashes (link);
1572 parent = g_path_get_dirname (link2);
1573 g_free (link2);
1575 resolved = g_build_filename (parent, symlink_value, NULL);
1576 g_free (parent);
1578 canonical = g_canonicalize_filename (resolved, NULL);
1580 g_free (resolved);
1582 return canonical;
1586 static char *
1587 get_parent (const char *path,
1588 dev_t *parent_dev)
1590 char *parent, *tmp;
1591 GStatBuf parent_stat;
1592 int num_recursions;
1593 char *path_copy;
1595 path_copy = strip_trailing_slashes (path);
1597 parent = g_path_get_dirname (path_copy);
1598 if (strcmp (parent, ".") == 0 ||
1599 strcmp (parent, path_copy) == 0)
1601 g_free (parent);
1602 g_free (path_copy);
1603 return NULL;
1605 g_free (path_copy);
1607 num_recursions = 0;
1608 do {
1609 if (g_lstat (parent, &parent_stat) != 0)
1611 g_free (parent);
1612 return NULL;
1615 if (S_ISLNK (parent_stat.st_mode))
1617 tmp = parent;
1618 parent = expand_symlink (parent);
1619 g_free (tmp);
1622 num_recursions++;
1623 if (num_recursions > 12)
1625 g_free (parent);
1626 return NULL;
1628 } while (S_ISLNK (parent_stat.st_mode));
1630 *parent_dev = parent_stat.st_dev;
1632 return parent;
1635 static char *
1636 expand_all_symlinks (const char *path)
1638 char *parent, *parent_expanded;
1639 char *basename, *res;
1640 dev_t parent_dev;
1642 parent = get_parent (path, &parent_dev);
1643 if (parent)
1645 parent_expanded = expand_all_symlinks (parent);
1646 g_free (parent);
1647 basename = g_path_get_basename (path);
1648 res = g_build_filename (parent_expanded, basename, NULL);
1649 g_free (basename);
1650 g_free (parent_expanded);
1652 else
1653 res = g_strdup (path);
1655 return res;
1658 static char *
1659 find_mountpoint_for (const char *file,
1660 dev_t dev)
1662 char *dir, *parent;
1663 dev_t dir_dev, parent_dev;
1665 dir = g_strdup (file);
1666 dir_dev = dev;
1668 while (1)
1670 parent = get_parent (dir, &parent_dev);
1671 if (parent == NULL)
1672 return dir;
1674 if (parent_dev != dir_dev)
1676 g_free (parent);
1677 return dir;
1680 g_free (dir);
1681 dir = parent;
1685 char *
1686 _g_local_file_find_topdir_for (const char *file)
1688 char *dir;
1689 char *mountpoint = NULL;
1690 dev_t dir_dev;
1692 dir = get_parent (file, &dir_dev);
1693 if (dir == NULL)
1694 return NULL;
1696 mountpoint = find_mountpoint_for (dir, dir_dev);
1697 g_free (dir);
1699 return mountpoint;
1702 static char *
1703 get_unique_filename (const char *basename,
1704 int id)
1706 const char *dot;
1708 if (id == 1)
1709 return g_strdup (basename);
1711 dot = strchr (basename, '.');
1712 if (dot)
1713 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1714 else
1715 return g_strdup_printf ("%s.%d", basename, id);
1718 static gboolean
1719 path_has_prefix (const char *path,
1720 const char *prefix)
1722 int prefix_len;
1724 if (prefix == NULL)
1725 return TRUE;
1727 prefix_len = strlen (prefix);
1729 if (strncmp (path, prefix, prefix_len) == 0 &&
1730 (prefix_len == 0 || /* empty prefix always matches */
1731 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1732 path[prefix_len] == 0 ||
1733 path[prefix_len] == '/'))
1734 return TRUE;
1736 return FALSE;
1739 static char *
1740 try_make_relative (const char *path,
1741 const char *base)
1743 char *path2, *base2;
1744 char *relative;
1746 path2 = expand_all_symlinks (path);
1747 base2 = expand_all_symlinks (base);
1749 relative = NULL;
1750 if (path_has_prefix (path2, base2))
1752 relative = path2 + strlen (base2);
1753 while (*relative == '/')
1754 relative ++;
1755 relative = g_strdup (relative);
1757 g_free (path2);
1758 g_free (base2);
1760 if (relative)
1761 return relative;
1763 /* Failed, use abs path */
1764 return g_strdup (path);
1767 gboolean
1768 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1770 static gsize home_dev_set = 0;
1771 static dev_t home_dev;
1772 char *topdir, *globaldir, *trashdir, *tmpname;
1773 uid_t uid;
1774 char uid_str[32];
1775 GStatBuf global_stat, trash_stat;
1776 gboolean res;
1777 GUnixMountEntry *mount;
1779 if (g_once_init_enter (&home_dev_set))
1781 GStatBuf home_stat;
1783 g_stat (g_get_home_dir (), &home_stat);
1784 home_dev = home_stat.st_dev;
1785 g_once_init_leave (&home_dev_set, 1);
1788 /* Assume we can trash to the home */
1789 if (dir_dev == home_dev)
1790 return TRUE;
1792 topdir = find_mountpoint_for (dirname, dir_dev);
1793 if (topdir == NULL)
1794 return FALSE;
1796 mount = g_unix_mount_at (topdir, NULL);
1797 if (mount == NULL || g_unix_mount_is_system_internal (mount))
1799 g_clear_pointer (&mount, g_unix_mount_free);
1800 g_free (topdir);
1802 return FALSE;
1805 g_clear_pointer (&mount, g_unix_mount_free);
1807 globaldir = g_build_filename (topdir, ".Trash", NULL);
1808 if (g_lstat (globaldir, &global_stat) == 0 &&
1809 S_ISDIR (global_stat.st_mode) &&
1810 (global_stat.st_mode & S_ISVTX) != 0)
1812 /* got a toplevel sysadmin created dir, assume we
1813 * can trash to it (we should be able to create a dir)
1814 * This fails for the FAT case where the ownership of
1815 * that dir would be wrong though..
1817 g_free (globaldir);
1818 g_free (topdir);
1819 return TRUE;
1821 g_free (globaldir);
1823 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1824 uid = geteuid ();
1825 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1827 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1828 trashdir = g_build_filename (topdir, tmpname, NULL);
1829 g_free (tmpname);
1831 if (g_lstat (trashdir, &trash_stat) == 0)
1833 g_free (topdir);
1834 g_free (trashdir);
1835 return S_ISDIR (trash_stat.st_mode) &&
1836 trash_stat.st_uid == uid;
1838 g_free (trashdir);
1840 /* User specific trash didn't exist, can we create it? */
1841 res = g_access (topdir, W_OK) == 0;
1842 g_free (topdir);
1844 return res;
1847 #ifdef G_OS_UNIX
1848 gboolean
1849 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1851 gboolean ret = FALSE;
1852 gchar *mount_dir = NULL;
1853 size_t mount_dir_len;
1854 GStatBuf statbuf;
1856 if (!g_str_has_suffix (path, "/lost+found"))
1857 goto out;
1859 mount_dir = find_mountpoint_for (path, path_dev);
1860 if (mount_dir == NULL)
1861 goto out;
1863 mount_dir_len = strlen (mount_dir);
1864 /* We special-case rootfs ('/') since it's the only case where
1865 * mount_dir ends in '/'
1867 if (mount_dir_len == 1)
1868 mount_dir_len--;
1869 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1870 goto out;
1872 if (g_lstat (path, &statbuf) != 0)
1873 goto out;
1875 if (!(S_ISDIR (statbuf.st_mode) &&
1876 statbuf.st_uid == 0 &&
1877 statbuf.st_gid == 0))
1878 goto out;
1880 ret = TRUE;
1882 out:
1883 g_free (mount_dir);
1884 return ret;
1886 #endif
1888 static gboolean
1889 g_local_file_trash (GFile *file,
1890 GCancellable *cancellable,
1891 GError **error)
1893 GLocalFile *local = G_LOCAL_FILE (file);
1894 GStatBuf file_stat, home_stat;
1895 const char *homedir;
1896 char *trashdir, *topdir, *infodir, *filesdir;
1897 char *basename, *trashname, *trashfile, *infoname, *infofile;
1898 char *original_name, *original_name_escaped;
1899 int i;
1900 char *data;
1901 char *path;
1902 gboolean is_homedir_trash;
1903 char *delete_time = NULL;
1904 int fd;
1905 GStatBuf trash_stat, global_stat;
1906 char *dirname, *globaldir;
1907 GVfsClass *class;
1908 GVfs *vfs;
1909 int errsv;
1911 if (g_lstat (local->filename, &file_stat) != 0)
1913 errsv = errno;
1915 g_set_io_error (error,
1916 _("Error trashing file %s: %s"),
1917 file, errsv);
1918 return FALSE;
1921 homedir = g_get_home_dir ();
1922 g_stat (homedir, &home_stat);
1924 is_homedir_trash = FALSE;
1925 trashdir = NULL;
1927 /* On overlayfs, a file's st_dev will be different to the home directory's.
1928 * We still want to create our trash directory under the home directory, so
1929 * instead we should stat the directory that the file we're deleting is in as
1930 * this will have the same st_dev.
1932 if (!S_ISDIR (file_stat.st_mode))
1934 path = g_path_get_dirname (local->filename);
1935 /* If the parent is a symlink to a different device then it might have
1936 * st_dev equal to the home directory's, in which case we will end up
1937 * trying to rename across a filesystem boundary, which doesn't work. So
1938 * we use g_stat here instead of g_lstat, to know where the symlink
1939 * points to. */
1940 g_stat (path, &file_stat);
1941 g_free (path);
1944 if (file_stat.st_dev == home_stat.st_dev)
1946 is_homedir_trash = TRUE;
1947 errno = 0;
1948 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1949 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1951 char *display_name;
1952 errsv = errno;
1954 display_name = g_filename_display_name (trashdir);
1955 g_set_error (error, G_IO_ERROR,
1956 g_io_error_from_errno (errsv),
1957 _("Unable to create trash dir %s: %s"),
1958 display_name, g_strerror (errsv));
1959 g_free (display_name);
1960 g_free (trashdir);
1961 return FALSE;
1963 topdir = g_strdup (g_get_user_data_dir ());
1965 else
1967 uid_t uid;
1968 char uid_str[32];
1969 GUnixMountEntry *mount;
1971 uid = geteuid ();
1972 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1974 topdir = _g_local_file_find_topdir_for (local->filename);
1975 if (topdir == NULL)
1977 g_set_io_error (error,
1978 _("Unable to find toplevel directory to trash %s"),
1979 file, ENOTSUP);
1980 return FALSE;
1983 mount = g_unix_mount_at (topdir, NULL);
1984 if (mount == NULL || g_unix_mount_is_system_internal (mount))
1986 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1987 _("Trashing on system internal mounts is not supported"));
1989 g_clear_pointer (&mount, g_unix_mount_free);
1990 g_free (topdir);
1992 return FALSE;
1995 g_clear_pointer (&mount, g_unix_mount_free);
1997 /* Try looking for global trash dir $topdir/.Trash/$uid */
1998 globaldir = g_build_filename (topdir, ".Trash", NULL);
1999 if (g_lstat (globaldir, &global_stat) == 0 &&
2000 S_ISDIR (global_stat.st_mode) &&
2001 (global_stat.st_mode & S_ISVTX) != 0)
2003 trashdir = g_build_filename (globaldir, uid_str, NULL);
2005 if (g_lstat (trashdir, &trash_stat) == 0)
2007 if (!S_ISDIR (trash_stat.st_mode) ||
2008 trash_stat.st_uid != uid)
2010 /* Not a directory or not owned by user, ignore */
2011 g_free (trashdir);
2012 trashdir = NULL;
2015 else if (g_mkdir (trashdir, 0700) == -1)
2017 g_free (trashdir);
2018 trashdir = NULL;
2021 g_free (globaldir);
2023 if (trashdir == NULL)
2025 gboolean tried_create;
2027 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2028 dirname = g_strdup_printf (".Trash-%s", uid_str);
2029 trashdir = g_build_filename (topdir, dirname, NULL);
2030 g_free (dirname);
2032 tried_create = FALSE;
2034 retry:
2035 if (g_lstat (trashdir, &trash_stat) == 0)
2037 if (!S_ISDIR (trash_stat.st_mode) ||
2038 trash_stat.st_uid != uid)
2040 /* Remove the failed directory */
2041 if (tried_create)
2042 g_remove (trashdir);
2044 /* Not a directory or not owned by user, ignore */
2045 g_free (trashdir);
2046 trashdir = NULL;
2049 else
2051 if (!tried_create &&
2052 g_mkdir (trashdir, 0700) != -1)
2054 /* Ensure that the created dir has the right uid etc.
2055 This might fail on e.g. a FAT dir */
2056 tried_create = TRUE;
2057 goto retry;
2059 else
2061 g_free (trashdir);
2062 trashdir = NULL;
2067 if (trashdir == NULL)
2069 g_free (topdir);
2070 g_set_io_error (error,
2071 _("Unable to find or create trash directory for %s"),
2072 file, G_IO_ERROR_NOT_SUPPORTED);
2073 return FALSE;
2077 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2079 infodir = g_build_filename (trashdir, "info", NULL);
2080 filesdir = g_build_filename (trashdir, "files", NULL);
2081 g_free (trashdir);
2083 /* Make sure we have the subdirectories */
2084 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2085 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2087 g_free (topdir);
2088 g_free (infodir);
2089 g_free (filesdir);
2090 g_set_io_error (error,
2091 _("Unable to find or create trash directory for %s"),
2092 file, G_IO_ERROR_NOT_SUPPORTED);
2093 return FALSE;
2096 basename = g_path_get_basename (local->filename);
2097 i = 1;
2098 trashname = NULL;
2099 infofile = NULL;
2100 do {
2101 g_free (trashname);
2102 g_free (infofile);
2104 trashname = get_unique_filename (basename, i++);
2105 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2106 infofile = g_build_filename (infodir, infoname, NULL);
2107 g_free (infoname);
2109 fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
2110 errsv = errno;
2111 } while (fd == -1 && errsv == EEXIST);
2113 g_free (basename);
2114 g_free (infodir);
2116 if (fd == -1)
2118 errsv = errno;
2120 g_free (filesdir);
2121 g_free (topdir);
2122 g_free (trashname);
2123 g_free (infofile);
2125 g_set_io_error (error,
2126 _("Unable to create trashing info file for %s: %s"),
2127 file, errsv);
2128 return FALSE;
2131 (void) g_close (fd, NULL);
2133 /* Write the full content of the info file before trashing to make
2134 * sure someone doesn't read an empty file. See #749314
2137 /* Use absolute names for homedir */
2138 if (is_homedir_trash)
2139 original_name = g_strdup (local->filename);
2140 else
2141 original_name = try_make_relative (local->filename, topdir);
2142 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2144 g_free (original_name);
2145 g_free (topdir);
2148 GDateTime *now = g_date_time_new_now_local ();
2149 if (now != NULL)
2150 delete_time = g_date_time_format (now, "%Y-%m-%dT%H:%M:%S");
2151 else
2152 delete_time = g_strdup ("9999-12-31T23:59:59");
2153 g_date_time_unref (now);
2156 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2157 original_name_escaped, delete_time);
2158 g_free (delete_time);
2160 g_file_set_contents (infofile, data, -1, NULL);
2162 /* TODO: Maybe we should verify that you can delete the file from the trash
2163 * before moving it? OTOH, that is hard, as it needs a recursive scan
2166 trashfile = g_build_filename (filesdir, trashname, NULL);
2168 g_free (filesdir);
2170 if (g_rename (local->filename, trashfile) == -1)
2172 errsv = errno;
2174 g_unlink (infofile);
2176 g_free (trashname);
2177 g_free (infofile);
2178 g_free (trashfile);
2180 if (errsv == EXDEV)
2181 /* The trash dir was actually on another fs anyway!?
2182 * This can happen when the same device is mounted multiple
2183 * times, or with bind mounts of the same fs.
2185 g_set_io_error (error,
2186 _("Unable to trash file %s across filesystem boundaries"),
2187 file, ENOTSUP);
2188 else
2189 g_set_io_error (error,
2190 _("Unable to trash file %s: %s"),
2191 file, errsv);
2192 return FALSE;
2195 vfs = g_vfs_get_default ();
2196 class = G_VFS_GET_CLASS (vfs);
2197 if (class->local_file_moved)
2198 class->local_file_moved (vfs, local->filename, trashfile);
2200 g_free (trashfile);
2202 /* TODO: Do we need to update mtime/atime here after the move? */
2204 g_free (infofile);
2205 g_free (data);
2207 g_free (original_name_escaped);
2208 g_free (trashname);
2210 return TRUE;
2212 #else /* G_OS_WIN32 */
2213 gboolean
2214 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2216 return FALSE; /* XXX ??? */
2219 static gboolean
2220 g_local_file_trash (GFile *file,
2221 GCancellable *cancellable,
2222 GError **error)
2224 GLocalFile *local = G_LOCAL_FILE (file);
2225 SHFILEOPSTRUCTW op = {0};
2226 gboolean success;
2227 wchar_t *wfilename;
2228 long len;
2230 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2231 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2232 wfilename = g_renew (wchar_t, wfilename, len + 2);
2233 wfilename[len + 1] = 0;
2235 op.wFunc = FO_DELETE;
2236 op.pFrom = wfilename;
2237 op.fFlags = FOF_ALLOWUNDO;
2239 success = SHFileOperationW (&op) == 0;
2241 if (success && op.fAnyOperationsAborted)
2243 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2244 g_cancellable_cancel (cancellable);
2245 g_set_io_error (error,
2246 _("Unable to trash file %s: %s"),
2247 file, ECANCELED);
2248 success = FALSE;
2250 else if (!success)
2251 g_set_io_error (error,
2252 _("Unable to trash file %s"),
2253 file, 0);
2255 g_free (wfilename);
2256 return success;
2258 #endif /* G_OS_WIN32 */
2260 static gboolean
2261 g_local_file_make_directory (GFile *file,
2262 GCancellable *cancellable,
2263 GError **error)
2265 GLocalFile *local = G_LOCAL_FILE (file);
2267 if (g_mkdir (local->filename, 0777) == -1)
2269 int errsv = errno;
2271 if (errsv == EINVAL)
2272 /* This must be an invalid filename, on e.g. FAT */
2273 g_set_error_literal (error, G_IO_ERROR,
2274 G_IO_ERROR_INVALID_FILENAME,
2275 _("Invalid filename"));
2276 else
2277 g_set_io_error (error,
2278 _("Error creating directory %s: %s"),
2279 file, errsv);
2280 return FALSE;
2283 return TRUE;
2286 static gboolean
2287 g_local_file_make_symbolic_link (GFile *file,
2288 const char *symlink_value,
2289 GCancellable *cancellable,
2290 GError **error)
2292 #ifdef HAVE_SYMLINK
2293 GLocalFile *local = G_LOCAL_FILE (file);
2295 if (symlink (symlink_value, local->filename) == -1)
2297 int errsv = errno;
2299 if (errsv == EINVAL)
2300 /* This must be an invalid filename, on e.g. FAT */
2301 g_set_error_literal (error, G_IO_ERROR,
2302 G_IO_ERROR_INVALID_FILENAME,
2303 _("Invalid filename"));
2304 else if (errsv == EPERM)
2305 g_set_error (error, G_IO_ERROR,
2306 G_IO_ERROR_NOT_SUPPORTED,
2307 _("Filesystem does not support symbolic links"));
2308 else
2309 g_set_io_error (error,
2310 _("Error making symbolic link %s: %s"),
2311 file, errsv);
2312 return FALSE;
2314 return TRUE;
2315 #else
2316 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Symbolic links not supported"));
2317 return FALSE;
2318 #endif
2322 static gboolean
2323 g_local_file_copy (GFile *source,
2324 GFile *destination,
2325 GFileCopyFlags flags,
2326 GCancellable *cancellable,
2327 GFileProgressCallback progress_callback,
2328 gpointer progress_callback_data,
2329 GError **error)
2331 /* Fall back to default copy */
2332 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2333 return FALSE;
2336 static gboolean
2337 g_local_file_move (GFile *source,
2338 GFile *destination,
2339 GFileCopyFlags flags,
2340 GCancellable *cancellable,
2341 GFileProgressCallback progress_callback,
2342 gpointer progress_callback_data,
2343 GError **error)
2345 GLocalFile *local_source, *local_destination;
2346 GStatBuf statbuf;
2347 gboolean destination_exist, source_is_dir;
2348 char *backup_name;
2349 int res;
2350 off_t source_size;
2351 GVfsClass *class;
2352 GVfs *vfs;
2354 if (!G_IS_LOCAL_FILE (source) ||
2355 !G_IS_LOCAL_FILE (destination))
2357 /* Fall back to default move */
2358 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2359 return FALSE;
2362 local_source = G_LOCAL_FILE (source);
2363 local_destination = G_LOCAL_FILE (destination);
2365 res = g_lstat (local_source->filename, &statbuf);
2366 if (res == -1)
2368 int errsv = errno;
2370 g_set_io_error (error,
2371 _("Error moving file %s: %s"),
2372 source, errsv);
2373 return FALSE;
2376 source_is_dir = S_ISDIR (statbuf.st_mode);
2377 source_size = statbuf.st_size;
2379 destination_exist = FALSE;
2380 res = g_lstat (local_destination->filename, &statbuf);
2381 if (res == 0)
2383 destination_exist = TRUE; /* Target file exists */
2385 if (flags & G_FILE_COPY_OVERWRITE)
2387 /* Always fail on dirs, even with overwrite */
2388 if (S_ISDIR (statbuf.st_mode))
2390 if (source_is_dir)
2391 g_set_error_literal (error,
2392 G_IO_ERROR,
2393 G_IO_ERROR_WOULD_MERGE,
2394 _("Can’t move directory over directory"));
2395 else
2396 g_set_error_literal (error,
2397 G_IO_ERROR,
2398 G_IO_ERROR_IS_DIRECTORY,
2399 _("Can’t copy over directory"));
2400 return FALSE;
2403 else
2405 g_set_io_error (error,
2406 _("Error moving file %s: %s"),
2407 source, EEXIST);
2408 return FALSE;
2412 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2414 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2415 if (g_rename (local_destination->filename, backup_name) == -1)
2417 g_set_error_literal (error,
2418 G_IO_ERROR,
2419 G_IO_ERROR_CANT_CREATE_BACKUP,
2420 _("Backup file creation failed"));
2421 g_free (backup_name);
2422 return FALSE;
2424 g_free (backup_name);
2425 destination_exist = FALSE; /* It did, but no more */
2428 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2430 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2431 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2432 res = g_unlink (local_destination->filename);
2433 if (res == -1)
2435 int errsv = errno;
2437 g_set_error (error, G_IO_ERROR,
2438 g_io_error_from_errno (errsv),
2439 _("Error removing target file: %s"),
2440 g_strerror (errsv));
2441 return FALSE;
2445 if (g_rename (local_source->filename, local_destination->filename) == -1)
2447 int errsv = errno;
2449 if (errsv == EXDEV)
2450 /* This will cause the fallback code to run */
2451 g_set_error_literal (error, G_IO_ERROR,
2452 G_IO_ERROR_NOT_SUPPORTED,
2453 _("Move between mounts not supported"));
2454 else if (errsv == EINVAL)
2455 /* This must be an invalid filename, on e.g. FAT, or
2456 we're trying to move the file into itself...
2457 We return invalid filename for both... */
2458 g_set_error_literal (error, G_IO_ERROR,
2459 G_IO_ERROR_INVALID_FILENAME,
2460 _("Invalid filename"));
2461 else
2462 g_set_io_error (error,
2463 _("Error moving file %s: %s"),
2464 source, errsv);
2465 return FALSE;
2468 vfs = g_vfs_get_default ();
2469 class = G_VFS_GET_CLASS (vfs);
2470 if (class->local_file_moved)
2471 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2473 /* Make sure we send full copied size */
2474 if (progress_callback)
2475 progress_callback (source_size, source_size, progress_callback_data);
2477 return TRUE;
2480 #ifdef G_OS_WIN32
2482 gboolean
2483 g_local_file_is_remote (const gchar *filename)
2485 return FALSE;
2488 #else
2490 static gboolean
2491 is_remote_fs (const gchar *filename)
2493 const char *fsname = NULL;
2495 #ifdef USE_STATFS
2496 struct statfs statfs_buffer;
2497 int statfs_result = 0;
2499 #if STATFS_ARGS == 2
2500 statfs_result = statfs (filename, &statfs_buffer);
2501 #elif STATFS_ARGS == 4
2502 statfs_result = statfs (filename, &statfs_buffer, sizeof (statfs_buffer), 0);
2503 #endif
2505 #elif defined(USE_STATVFS)
2506 struct statvfs statfs_buffer;
2507 int statfs_result = 0;
2509 statfs_result = statvfs (filename, &statfs_buffer);
2510 #else
2511 return FALSE;
2512 #endif
2514 if (statfs_result == -1)
2515 return FALSE;
2517 #ifdef USE_STATFS
2518 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
2519 fsname = statfs_buffer.f_fstypename;
2520 #else
2521 fsname = get_fs_type (statfs_buffer.f_type);
2522 #endif
2524 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
2525 fsname = statfs_buffer.f_basetype;
2526 #endif
2528 if (fsname != NULL)
2530 if (strcmp (fsname, "nfs") == 0)
2531 return TRUE;
2532 if (strcmp (fsname, "nfs4") == 0)
2533 return TRUE;
2536 return FALSE;
2539 gboolean
2540 g_local_file_is_remote (const gchar *filename)
2542 static gboolean remote_home;
2543 static gsize initialized;
2544 const gchar *home;
2546 home = g_get_home_dir ();
2547 if (path_has_prefix (filename, home))
2549 if (g_once_init_enter (&initialized))
2551 remote_home = is_remote_fs (home);
2552 g_once_init_leave (&initialized, TRUE);
2554 return remote_home;
2557 return FALSE;
2559 #endif /* !G_OS_WIN32 */
2561 static GFileMonitor*
2562 g_local_file_monitor_dir (GFile *file,
2563 GFileMonitorFlags flags,
2564 GCancellable *cancellable,
2565 GError **error)
2567 GLocalFile *local_file = G_LOCAL_FILE (file);
2569 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2572 static GFileMonitor*
2573 g_local_file_monitor_file (GFile *file,
2574 GFileMonitorFlags flags,
2575 GCancellable *cancellable,
2576 GError **error)
2578 GLocalFile *local_file = G_LOCAL_FILE (file);
2580 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2583 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2585 * If available, we use fopenat() in preference to filenames for
2586 * efficiency and safety reasons. We know that fopenat() is available
2587 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2588 * defined as a macro.
2590 * We use a linked list of stack-allocated GSList nodes in order to be
2591 * able to reconstruct the filename for error messages. We actually
2592 * pass the filename to operate on through the top node of the list.
2594 * In case we're using openat(), this top filename will be a basename
2595 * which should be opened in the directory which has also had its fd
2596 * passed along. If we're not using openat() then it will be a full
2597 * absolute filename.
2600 static gboolean
2601 g_local_file_measure_size_error (GFileMeasureFlags flags,
2602 gint saved_errno,
2603 GSList *name,
2604 GError **error)
2606 /* Only report an error if we were at the toplevel or if the caller
2607 * requested reporting of all errors.
2609 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2611 GString *filename;
2612 GSList *node;
2614 /* Skip some work if there is no error return */
2615 if (!error)
2616 return FALSE;
2618 #ifdef AT_FDCWD
2619 /* If using openat() we need to rebuild the filename for the message */
2620 filename = g_string_new (name->data);
2621 for (node = name->next; node; node = node->next)
2623 gchar *utf8;
2625 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2626 utf8 = g_filename_display_name (node->data);
2627 g_string_prepend (filename, utf8);
2628 g_free (utf8);
2630 #else
2632 gchar *utf8;
2634 /* Otherwise, we already have it, so just use it. */
2635 node = name;
2636 filename = g_string_new (NULL);
2637 utf8 = g_filename_display_name (node->data);
2638 g_string_append (filename, utf8);
2639 g_free (utf8);
2641 #endif
2643 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2644 _("Could not determine the disk usage of %s: %s"),
2645 filename->str, g_strerror (saved_errno));
2647 g_string_free (filename, TRUE);
2649 return FALSE;
2652 else
2653 /* We're not reporting this error... */
2654 return TRUE;
2657 typedef struct
2659 GFileMeasureFlags flags;
2660 dev_t contained_on;
2661 GCancellable *cancellable;
2663 GFileMeasureProgressCallback progress_callback;
2664 gpointer progress_data;
2666 guint64 disk_usage;
2667 guint64 num_dirs;
2668 guint64 num_files;
2670 guint64 last_progress_report;
2671 } MeasureState;
2673 static gboolean
2674 g_local_file_measure_size_of_contents (gint fd,
2675 GSList *dir_name,
2676 MeasureState *state,
2677 GError **error);
2679 static gboolean
2680 g_local_file_measure_size_of_file (gint parent_fd,
2681 GSList *name,
2682 MeasureState *state,
2683 GError **error)
2685 GLocalFileStat buf;
2687 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2688 return FALSE;
2690 #if defined (AT_FDCWD)
2691 if (fstatat (parent_fd, name->data, &buf, AT_SYMLINK_NOFOLLOW) != 0)
2693 int errsv = errno;
2694 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2696 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2697 if (g_lstat (name->data, &buf) != 0)
2699 int errsv = errno;
2700 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2702 #else /* !AT_FDCWD && !HAVE_LSTAT && G_OS_WIN32 */
2703 if (GLIB_PRIVATE_CALL (g_win32_lstat_utf8) (name->data, &buf) != 0)
2705 int errsv = errno;
2706 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2708 #endif
2710 if (name->next)
2712 /* If not at the toplevel, check for a device boundary. */
2714 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2715 if (state->contained_on != buf.st_dev)
2716 return TRUE;
2718 else
2720 /* If, however, this is the toplevel, set the device number so
2721 * that recursive invocations can compare against it.
2723 state->contained_on = buf.st_dev;
2726 #if defined (G_OS_WIN32)
2727 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2728 state->disk_usage += buf.allocated_size;
2729 else
2730 #elif defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2731 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2732 state->disk_usage += buf.st_blocks * G_GUINT64_CONSTANT (512);
2733 else
2734 #endif
2735 state->disk_usage += buf.st_size;
2737 if (S_ISDIR (buf.st_mode))
2738 state->num_dirs++;
2739 else
2740 state->num_files++;
2742 if (state->progress_callback)
2744 /* We could attempt to do some cleverness here in order to avoid
2745 * calling clock_gettime() so much, but we're doing stats and opens
2746 * all over the place already...
2748 if (state->last_progress_report)
2750 guint64 now;
2752 now = g_get_monotonic_time ();
2754 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2756 (* state->progress_callback) (TRUE,
2757 state->disk_usage, state->num_dirs, state->num_files,
2758 state->progress_data);
2759 state->last_progress_report = now;
2762 else
2764 /* We must do an initial report to inform that more reports
2765 * will be coming.
2767 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2768 state->last_progress_report = g_get_monotonic_time ();
2772 if (S_ISDIR (buf.st_mode))
2774 int dir_fd = -1;
2775 #ifdef AT_FDCWD
2776 int errsv;
2777 #endif
2779 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2780 return FALSE;
2782 #ifdef AT_FDCWD
2783 #ifdef HAVE_OPEN_O_DIRECTORY
2784 dir_fd = openat (parent_fd, name->data, O_RDONLY|O_DIRECTORY);
2785 #else
2786 dir_fd = openat (parent_fd, name->data, O_RDONLY);
2787 #endif
2788 errsv = errno;
2789 if (dir_fd < 0)
2790 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2791 #endif
2793 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2794 return FALSE;
2797 return TRUE;
2800 static gboolean
2801 g_local_file_measure_size_of_contents (gint fd,
2802 GSList *dir_name,
2803 MeasureState *state,
2804 GError **error)
2806 gboolean success = TRUE;
2807 const gchar *name;
2808 GDir *dir;
2810 #ifdef AT_FDCWD
2812 /* If this fails, we want to preserve the errno from fopendir() */
2813 DIR *dirp;
2814 dirp = fdopendir (fd);
2815 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2817 #else
2818 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2819 #endif
2821 if (dir == NULL)
2823 gint saved_errno = errno;
2825 #ifdef AT_FDCWD
2826 close (fd);
2827 #endif
2829 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2832 while (success && (name = g_dir_read_name (dir)))
2834 GSList node;
2836 node.next = dir_name;
2837 #ifdef AT_FDCWD
2838 node.data = (gchar *) name;
2839 #else
2840 node.data = g_build_filename (dir_name->data, name, NULL);
2841 #endif
2843 success = g_local_file_measure_size_of_file (fd, &node, state, error);
2845 #ifndef AT_FDCWD
2846 g_free (node.data);
2847 #endif
2850 g_dir_close (dir);
2852 return success;
2855 static gboolean
2856 g_local_file_measure_disk_usage (GFile *file,
2857 GFileMeasureFlags flags,
2858 GCancellable *cancellable,
2859 GFileMeasureProgressCallback progress_callback,
2860 gpointer progress_data,
2861 guint64 *disk_usage,
2862 guint64 *num_dirs,
2863 guint64 *num_files,
2864 GError **error)
2866 GLocalFile *local_file = G_LOCAL_FILE (file);
2867 MeasureState state = { 0, };
2868 gint root_fd = -1;
2869 GSList node;
2871 state.flags = flags;
2872 state.cancellable = cancellable;
2873 state.progress_callback = progress_callback;
2874 state.progress_data = progress_data;
2876 #ifdef AT_FDCWD
2877 root_fd = AT_FDCWD;
2878 #endif
2880 node.data = local_file->filename;
2881 node.next = NULL;
2883 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
2884 return FALSE;
2886 if (disk_usage)
2887 *disk_usage = state.disk_usage;
2889 if (num_dirs)
2890 *num_dirs = state.num_dirs;
2892 if (num_files)
2893 *num_files = state.num_files;
2895 return TRUE;
2898 static void
2899 g_local_file_file_iface_init (GFileIface *iface)
2901 iface->dup = g_local_file_dup;
2902 iface->hash = g_local_file_hash;
2903 iface->equal = g_local_file_equal;
2904 iface->is_native = g_local_file_is_native;
2905 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2906 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2907 iface->get_basename = g_local_file_get_basename;
2908 iface->get_path = g_local_file_get_path;
2909 iface->get_uri = g_local_file_get_uri;
2910 iface->get_parse_name = g_local_file_get_parse_name;
2911 iface->get_parent = g_local_file_get_parent;
2912 iface->prefix_matches = g_local_file_prefix_matches;
2913 iface->get_relative_path = g_local_file_get_relative_path;
2914 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2915 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2916 iface->set_display_name = g_local_file_set_display_name;
2917 iface->enumerate_children = g_local_file_enumerate_children;
2918 iface->query_info = g_local_file_query_info;
2919 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2920 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2921 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2922 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2923 iface->set_attribute = g_local_file_set_attribute;
2924 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2925 iface->read_fn = g_local_file_read;
2926 iface->append_to = g_local_file_append_to;
2927 iface->create = g_local_file_create;
2928 iface->replace = g_local_file_replace;
2929 iface->open_readwrite = g_local_file_open_readwrite;
2930 iface->create_readwrite = g_local_file_create_readwrite;
2931 iface->replace_readwrite = g_local_file_replace_readwrite;
2932 iface->delete_file = g_local_file_delete;
2933 iface->trash = g_local_file_trash;
2934 iface->make_directory = g_local_file_make_directory;
2935 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2936 iface->copy = g_local_file_copy;
2937 iface->move = g_local_file_move;
2938 iface->monitor_dir = g_local_file_monitor_dir;
2939 iface->monitor_file = g_local_file_monitor_file;
2940 iface->measure_disk_usage = g_local_file_measure_disk_usage;
2942 iface->supports_thread_contexts = TRUE;