Merge branch 'test-ip_mreq_source-android-only' into 'master'
[glib.git] / gio / glocalfile.c
blob354ac7c8cb8a955c2cf84696b171c9a93aa9e5e7
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".
990 #ifndef G_OS_WIN32
991 if (statfs_result == 0 &&
992 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
993 no_size = TRUE;
994 #endif /* G_OS_WIN32 */
996 #elif defined(USE_STATVFS)
997 statfs_result = statvfs (local->filename, &statfs_buffer);
998 block_size = statfs_buffer.f_frsize;
999 #endif /* USE_STATFS */
1001 if (statfs_result == -1)
1003 int errsv = errno;
1005 g_set_io_error (error,
1006 _("Error getting filesystem info for %s: %s"),
1007 file, errsv);
1008 return NULL;
1011 info = g_file_info_new ();
1013 attribute_matcher = g_file_attribute_matcher_new (attributes);
1015 if (!no_size &&
1016 g_file_attribute_matcher_matches (attribute_matcher,
1017 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1019 #ifdef G_OS_WIN32
1020 gchar *localdir = g_path_get_dirname (local->filename);
1021 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1022 ULARGE_INTEGER li;
1024 g_free (localdir);
1025 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1026 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1027 g_free (wdirname);
1028 #else
1029 #if defined(USE_STATFS) || defined(USE_STATVFS)
1030 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1031 #endif
1032 #endif
1034 if (!no_size &&
1035 g_file_attribute_matcher_matches (attribute_matcher,
1036 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1038 #ifdef G_OS_WIN32
1039 gchar *localdir = g_path_get_dirname (local->filename);
1040 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1041 ULARGE_INTEGER li;
1043 g_free (localdir);
1044 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1045 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1046 g_free (wdirname);
1047 #else
1048 #if defined(USE_STATFS) || defined(USE_STATVFS)
1049 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1050 #endif
1051 #endif /* G_OS_WIN32 */
1054 if (!no_size &&
1055 g_file_attribute_matcher_matches (attribute_matcher,
1056 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1058 #ifdef G_OS_WIN32
1059 gchar *localdir = g_path_get_dirname (local->filename);
1060 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1061 ULARGE_INTEGER li_free;
1062 ULARGE_INTEGER li_total;
1064 g_free (localdir);
1065 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1066 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1067 g_free (wdirname);
1068 #else
1069 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1070 #endif /* G_OS_WIN32 */
1073 #ifndef G_OS_WIN32
1074 #ifdef USE_STATFS
1075 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1076 fstype = statfs_buffer.f_fstypename;
1077 #else
1078 fstype = get_fs_type (statfs_buffer.f_type);
1079 #endif
1081 #elif defined(USE_STATVFS)
1082 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1083 fstype = statfs_buffer.f_fstypename;
1084 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1085 fstype = statfs_buffer.f_basetype;
1086 #else
1087 fstype = NULL;
1088 #endif
1089 #endif /* USE_STATFS */
1091 if (fstype &&
1092 g_file_attribute_matcher_matches (attribute_matcher,
1093 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1094 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1095 #endif /* G_OS_WIN32 */
1097 if (g_file_attribute_matcher_matches (attribute_matcher,
1098 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1100 #ifdef G_OS_WIN32
1101 get_filesystem_readonly (info, local->filename);
1102 #else
1103 get_mount_info (info, local->filename, attribute_matcher);
1104 #endif /* G_OS_WIN32 */
1107 if (g_file_attribute_matcher_matches (attribute_matcher,
1108 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
1109 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE,
1110 g_local_file_is_remote (local->filename));
1112 g_file_attribute_matcher_unref (attribute_matcher);
1114 return info;
1117 static GMount *
1118 g_local_file_find_enclosing_mount (GFile *file,
1119 GCancellable *cancellable,
1120 GError **error)
1122 GLocalFile *local = G_LOCAL_FILE (file);
1123 GStatBuf buf;
1124 char *mountpoint;
1125 GMount *mount;
1127 if (g_lstat (local->filename, &buf) != 0)
1128 goto error;
1130 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1131 if (mountpoint == NULL)
1132 goto error;
1134 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1135 g_free (mountpoint);
1136 if (mount)
1137 return mount;
1139 error:
1140 g_set_io_error (error,
1141 /* Translators: This is an error message when trying to find
1142 * the enclosing (user visible) mount of a file, but none
1143 * exists.
1145 _("Containing mount for file %s not found"),
1146 file, 0);
1148 return NULL;
1151 static GFile *
1152 g_local_file_set_display_name (GFile *file,
1153 const char *display_name,
1154 GCancellable *cancellable,
1155 GError **error)
1157 GLocalFile *local, *new_local;
1158 GFile *new_file, *parent;
1159 GStatBuf statbuf;
1160 GVfsClass *class;
1161 GVfs *vfs;
1162 int errsv;
1164 parent = g_file_get_parent (file);
1165 if (parent == NULL)
1167 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1168 _("Can’t rename root directory"));
1169 return NULL;
1172 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1173 g_object_unref (parent);
1175 if (new_file == NULL)
1176 return NULL;
1177 local = G_LOCAL_FILE (file);
1178 new_local = G_LOCAL_FILE (new_file);
1180 if (g_lstat (new_local->filename, &statbuf) == -1)
1182 errsv = errno;
1184 if (errsv != ENOENT)
1186 g_set_io_error (error, _("Error renaming file %s: %s"), new_file, errsv);
1187 return NULL;
1190 else
1192 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
1193 _("Can’t rename file, filename already exists"));
1194 return NULL;
1197 if (g_rename (local->filename, new_local->filename) == -1)
1199 errsv = errno;
1201 if (errsv == EINVAL)
1202 /* We can't get a rename file into itself error here,
1203 * so this must be an invalid filename, on e.g. FAT
1205 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME,
1206 _("Invalid filename"));
1207 else
1208 g_set_io_error (error,
1209 _("Error renaming file %s: %s"),
1210 file, errsv);
1211 g_object_unref (new_file);
1212 return NULL;
1215 vfs = g_vfs_get_default ();
1216 class = G_VFS_GET_CLASS (vfs);
1217 if (class->local_file_moved)
1218 class->local_file_moved (vfs, local->filename, new_local->filename);
1220 return new_file;
1223 static GFileInfo *
1224 g_local_file_query_info (GFile *file,
1225 const char *attributes,
1226 GFileQueryInfoFlags flags,
1227 GCancellable *cancellable,
1228 GError **error)
1230 GLocalFile *local = G_LOCAL_FILE (file);
1231 GFileInfo *info;
1232 GFileAttributeMatcher *matcher;
1233 char *basename, *dirname;
1234 GLocalParentFileInfo parent_info;
1236 matcher = g_file_attribute_matcher_new (attributes);
1238 basename = g_path_get_basename (local->filename);
1240 dirname = g_path_get_dirname (local->filename);
1241 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1242 g_free (dirname);
1244 info = _g_local_file_info_get (basename, local->filename,
1245 matcher, flags, &parent_info,
1246 error);
1249 _g_local_file_info_free_parent_info (&parent_info);
1250 g_free (basename);
1252 g_file_attribute_matcher_unref (matcher);
1254 return info;
1257 static GFileAttributeInfoList *
1258 g_local_file_query_settable_attributes (GFile *file,
1259 GCancellable *cancellable,
1260 GError **error)
1262 return g_file_attribute_info_list_ref (local_writable_attributes);
1265 static GFileAttributeInfoList *
1266 g_local_file_query_writable_namespaces (GFile *file,
1267 GCancellable *cancellable,
1268 GError **error)
1270 GFileAttributeInfoList *list;
1271 GVfsClass *class;
1272 GVfs *vfs;
1274 if (g_once_init_enter (&local_writable_namespaces))
1276 /* Writable namespaces: */
1278 list = g_file_attribute_info_list_new ();
1280 #ifdef HAVE_XATTR
1281 g_file_attribute_info_list_add (list,
1282 "xattr",
1283 G_FILE_ATTRIBUTE_TYPE_STRING,
1284 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1285 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1286 g_file_attribute_info_list_add (list,
1287 "xattr-sys",
1288 G_FILE_ATTRIBUTE_TYPE_STRING,
1289 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1290 #endif
1292 vfs = g_vfs_get_default ();
1293 class = G_VFS_GET_CLASS (vfs);
1294 if (class->add_writable_namespaces)
1295 class->add_writable_namespaces (vfs, list);
1297 g_once_init_leave (&local_writable_namespaces, (gsize)list);
1299 list = (GFileAttributeInfoList *)local_writable_namespaces;
1301 return g_file_attribute_info_list_ref (list);
1304 static gboolean
1305 g_local_file_set_attribute (GFile *file,
1306 const char *attribute,
1307 GFileAttributeType type,
1308 gpointer value_p,
1309 GFileQueryInfoFlags flags,
1310 GCancellable *cancellable,
1311 GError **error)
1313 GLocalFile *local = G_LOCAL_FILE (file);
1315 return _g_local_file_info_set_attribute (local->filename,
1316 attribute,
1317 type,
1318 value_p,
1319 flags,
1320 cancellable,
1321 error);
1324 static gboolean
1325 g_local_file_set_attributes_from_info (GFile *file,
1326 GFileInfo *info,
1327 GFileQueryInfoFlags flags,
1328 GCancellable *cancellable,
1329 GError **error)
1331 GLocalFile *local = G_LOCAL_FILE (file);
1332 int res, chained_res;
1333 GFileIface *default_iface;
1335 res = _g_local_file_info_set_attributes (local->filename,
1336 info, flags,
1337 cancellable,
1338 error);
1340 if (!res)
1341 error = NULL; /* Don't write over error if further errors */
1343 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1345 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1347 return res && chained_res;
1350 static GFileInputStream *
1351 g_local_file_read (GFile *file,
1352 GCancellable *cancellable,
1353 GError **error)
1355 GLocalFile *local = G_LOCAL_FILE (file);
1356 int fd, ret;
1357 GLocalFileStat buf;
1359 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1360 if (fd == -1)
1362 int errsv = errno;
1364 #ifdef G_OS_WIN32
1365 if (errsv == EACCES)
1367 /* Exploit the fact that on W32 the glib filename encoding is UTF8 */
1368 ret = GLIB_PRIVATE_CALL (g_win32_stat_utf8) (local->filename, &buf);
1369 if (ret == 0 && S_ISDIR (buf.st_mode))
1370 errsv = EISDIR;
1372 #endif
1373 g_set_io_error (error,
1374 _("Error opening file %s: %s"),
1375 file, errsv);
1376 return NULL;
1379 #ifdef G_OS_WIN32
1380 ret = GLIB_PRIVATE_CALL (g_win32_fstat) (fd, &buf);
1381 #else
1382 ret = fstat (fd, &buf);
1383 #endif
1385 if (ret == 0 && S_ISDIR (buf.st_mode))
1387 (void) g_close (fd, NULL);
1388 g_set_io_error (error,
1389 _("Error opening file %s: %s"),
1390 file, EISDIR);
1391 return NULL;
1394 return _g_local_file_input_stream_new (fd);
1397 static GFileOutputStream *
1398 g_local_file_append_to (GFile *file,
1399 GFileCreateFlags flags,
1400 GCancellable *cancellable,
1401 GError **error)
1403 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1404 flags, cancellable, error);
1407 static GFileOutputStream *
1408 g_local_file_create (GFile *file,
1409 GFileCreateFlags flags,
1410 GCancellable *cancellable,
1411 GError **error)
1413 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1414 FALSE, flags, NULL,
1415 cancellable, error);
1418 static GFileOutputStream *
1419 g_local_file_replace (GFile *file,
1420 const char *etag,
1421 gboolean make_backup,
1422 GFileCreateFlags flags,
1423 GCancellable *cancellable,
1424 GError **error)
1426 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1427 FALSE,
1428 etag, make_backup, flags, NULL,
1429 cancellable, error);
1432 static GFileIOStream *
1433 g_local_file_open_readwrite (GFile *file,
1434 GCancellable *cancellable,
1435 GError **error)
1437 GFileOutputStream *output;
1438 GFileIOStream *res;
1440 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1441 TRUE,
1442 cancellable, error);
1443 if (output == NULL)
1444 return NULL;
1446 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1447 g_object_unref (output);
1448 return res;
1451 static GFileIOStream *
1452 g_local_file_create_readwrite (GFile *file,
1453 GFileCreateFlags flags,
1454 GCancellable *cancellable,
1455 GError **error)
1457 GFileOutputStream *output;
1458 GFileIOStream *res;
1460 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1461 TRUE, flags, NULL,
1462 cancellable, error);
1463 if (output == NULL)
1464 return NULL;
1466 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1467 g_object_unref (output);
1468 return res;
1471 static GFileIOStream *
1472 g_local_file_replace_readwrite (GFile *file,
1473 const char *etag,
1474 gboolean make_backup,
1475 GFileCreateFlags flags,
1476 GCancellable *cancellable,
1477 GError **error)
1479 GFileOutputStream *output;
1480 GFileIOStream *res;
1482 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1483 TRUE,
1484 etag, make_backup, flags, NULL,
1485 cancellable, error);
1486 if (output == NULL)
1487 return NULL;
1489 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1490 g_object_unref (output);
1491 return res;
1494 static gboolean
1495 g_local_file_delete (GFile *file,
1496 GCancellable *cancellable,
1497 GError **error)
1499 GLocalFile *local = G_LOCAL_FILE (file);
1500 GVfsClass *class;
1501 GVfs *vfs;
1503 if (g_remove (local->filename) == -1)
1505 int errsv = errno;
1507 /* Posix allows EEXIST too, but the more sane error
1508 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1509 expects */
1510 if (errsv == EEXIST)
1511 errsv = ENOTEMPTY;
1513 g_set_io_error (error,
1514 _("Error removing file %s: %s"),
1515 file, errsv);
1516 return FALSE;
1519 vfs = g_vfs_get_default ();
1520 class = G_VFS_GET_CLASS (vfs);
1521 if (class->local_file_removed)
1522 class->local_file_removed (vfs, local->filename);
1524 return TRUE;
1527 #ifndef G_OS_WIN32
1529 static char *
1530 strip_trailing_slashes (const char *path)
1532 char *path_copy;
1533 int len;
1535 path_copy = g_strdup (path);
1536 len = strlen (path_copy);
1537 while (len > 1 && path_copy[len-1] == '/')
1538 path_copy[--len] = 0;
1540 return path_copy;
1543 static char *
1544 expand_symlink (const char *link)
1546 char *resolved, *canonical, *parent, *link2;
1547 char symlink_value[4096];
1548 #ifdef G_OS_WIN32
1549 #else
1550 gssize res;
1551 #endif
1553 #ifdef G_OS_WIN32
1554 #else
1555 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1557 if (res == -1)
1558 return g_strdup (link);
1559 symlink_value[res] = 0;
1560 #endif
1562 if (g_path_is_absolute (symlink_value))
1563 return g_canonicalize_filename (symlink_value, NULL);
1564 else
1566 link2 = strip_trailing_slashes (link);
1567 parent = g_path_get_dirname (link2);
1568 g_free (link2);
1570 resolved = g_build_filename (parent, symlink_value, NULL);
1571 g_free (parent);
1573 canonical = g_canonicalize_filename (resolved, NULL);
1575 g_free (resolved);
1577 return canonical;
1581 static char *
1582 get_parent (const char *path,
1583 dev_t *parent_dev)
1585 char *parent, *tmp;
1586 GStatBuf parent_stat;
1587 int num_recursions;
1588 char *path_copy;
1590 path_copy = strip_trailing_slashes (path);
1592 parent = g_path_get_dirname (path_copy);
1593 if (strcmp (parent, ".") == 0 ||
1594 strcmp (parent, path_copy) == 0)
1596 g_free (parent);
1597 g_free (path_copy);
1598 return NULL;
1600 g_free (path_copy);
1602 num_recursions = 0;
1603 do {
1604 if (g_lstat (parent, &parent_stat) != 0)
1606 g_free (parent);
1607 return NULL;
1610 if (S_ISLNK (parent_stat.st_mode))
1612 tmp = parent;
1613 parent = expand_symlink (parent);
1614 g_free (tmp);
1617 num_recursions++;
1618 if (num_recursions > 12)
1620 g_free (parent);
1621 return NULL;
1623 } while (S_ISLNK (parent_stat.st_mode));
1625 *parent_dev = parent_stat.st_dev;
1627 return parent;
1630 static char *
1631 expand_all_symlinks (const char *path)
1633 char *parent, *parent_expanded;
1634 char *basename, *res;
1635 dev_t parent_dev;
1637 parent = get_parent (path, &parent_dev);
1638 if (parent)
1640 parent_expanded = expand_all_symlinks (parent);
1641 g_free (parent);
1642 basename = g_path_get_basename (path);
1643 res = g_build_filename (parent_expanded, basename, NULL);
1644 g_free (basename);
1645 g_free (parent_expanded);
1647 else
1648 res = g_strdup (path);
1650 return res;
1653 static char *
1654 find_mountpoint_for (const char *file,
1655 dev_t dev)
1657 char *dir, *parent;
1658 dev_t dir_dev, parent_dev;
1660 dir = g_strdup (file);
1661 dir_dev = dev;
1663 while (1)
1665 parent = get_parent (dir, &parent_dev);
1666 if (parent == NULL)
1667 return dir;
1669 if (parent_dev != dir_dev)
1671 g_free (parent);
1672 return dir;
1675 g_free (dir);
1676 dir = parent;
1680 static char *
1681 _g_local_file_find_topdir_for_internal (const char *file, dev_t file_dev)
1683 char *dir;
1684 char *mountpoint = NULL;
1685 dev_t dir_dev;
1687 dir = get_parent (file, &dir_dev);
1688 if (dir == NULL || dir_dev != file_dev)
1690 g_free (dir);
1692 return NULL;
1695 mountpoint = find_mountpoint_for (dir, dir_dev);
1696 g_free (dir);
1698 return mountpoint;
1701 char *
1702 _g_local_file_find_topdir_for (const char *file)
1704 GStatBuf file_stat;
1706 if (g_lstat (file, &file_stat) != 0)
1707 return NULL;
1709 return _g_local_file_find_topdir_for_internal (file, file_stat.st_dev);
1712 static char *
1713 get_unique_filename (const char *basename,
1714 int id)
1716 const char *dot;
1718 if (id == 1)
1719 return g_strdup (basename);
1721 dot = strchr (basename, '.');
1722 if (dot)
1723 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1724 else
1725 return g_strdup_printf ("%s.%d", basename, id);
1728 static gboolean
1729 path_has_prefix (const char *path,
1730 const char *prefix)
1732 int prefix_len;
1734 if (prefix == NULL)
1735 return TRUE;
1737 prefix_len = strlen (prefix);
1739 if (strncmp (path, prefix, prefix_len) == 0 &&
1740 (prefix_len == 0 || /* empty prefix always matches */
1741 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1742 path[prefix_len] == 0 ||
1743 path[prefix_len] == '/'))
1744 return TRUE;
1746 return FALSE;
1749 static char *
1750 try_make_relative (const char *path,
1751 const char *base)
1753 char *path2, *base2;
1754 char *relative;
1756 path2 = expand_all_symlinks (path);
1757 base2 = expand_all_symlinks (base);
1759 relative = NULL;
1760 if (path_has_prefix (path2, base2))
1762 relative = path2 + strlen (base2);
1763 while (*relative == '/')
1764 relative ++;
1765 relative = g_strdup (relative);
1767 g_free (path2);
1768 g_free (base2);
1770 if (relative)
1771 return relative;
1773 /* Failed, use abs path */
1774 return g_strdup (path);
1777 gboolean
1778 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1780 static gsize home_dev_set = 0;
1781 static dev_t home_dev;
1782 char *topdir, *globaldir, *trashdir, *tmpname;
1783 uid_t uid;
1784 char uid_str[32];
1785 GStatBuf global_stat, trash_stat;
1786 gboolean res;
1787 GUnixMountEntry *mount;
1789 if (g_once_init_enter (&home_dev_set))
1791 GStatBuf home_stat;
1793 g_stat (g_get_home_dir (), &home_stat);
1794 home_dev = home_stat.st_dev;
1795 g_once_init_leave (&home_dev_set, 1);
1798 /* Assume we can trash to the home */
1799 if (dir_dev == home_dev)
1800 return TRUE;
1802 topdir = find_mountpoint_for (dirname, dir_dev);
1803 if (topdir == NULL)
1804 return FALSE;
1806 mount = g_unix_mount_at (topdir, NULL);
1807 if (mount == NULL || g_unix_mount_is_system_internal (mount))
1809 g_clear_pointer (&mount, g_unix_mount_free);
1810 g_free (topdir);
1812 return FALSE;
1815 g_clear_pointer (&mount, g_unix_mount_free);
1817 globaldir = g_build_filename (topdir, ".Trash", NULL);
1818 if (g_lstat (globaldir, &global_stat) == 0 &&
1819 S_ISDIR (global_stat.st_mode) &&
1820 (global_stat.st_mode & S_ISVTX) != 0)
1822 /* got a toplevel sysadmin created dir, assume we
1823 * can trash to it (we should be able to create a dir)
1824 * This fails for the FAT case where the ownership of
1825 * that dir would be wrong though..
1827 g_free (globaldir);
1828 g_free (topdir);
1829 return TRUE;
1831 g_free (globaldir);
1833 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1834 uid = geteuid ();
1835 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1837 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1838 trashdir = g_build_filename (topdir, tmpname, NULL);
1839 g_free (tmpname);
1841 if (g_lstat (trashdir, &trash_stat) == 0)
1843 g_free (topdir);
1844 g_free (trashdir);
1845 return S_ISDIR (trash_stat.st_mode) &&
1846 trash_stat.st_uid == uid;
1848 g_free (trashdir);
1850 /* User specific trash didn't exist, can we create it? */
1851 res = g_access (topdir, W_OK) == 0;
1852 g_free (topdir);
1854 return res;
1857 #ifdef G_OS_UNIX
1858 gboolean
1859 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1861 gboolean ret = FALSE;
1862 gchar *mount_dir = NULL;
1863 size_t mount_dir_len;
1864 GStatBuf statbuf;
1866 if (!g_str_has_suffix (path, "/lost+found"))
1867 goto out;
1869 mount_dir = find_mountpoint_for (path, path_dev);
1870 if (mount_dir == NULL)
1871 goto out;
1873 mount_dir_len = strlen (mount_dir);
1874 /* We special-case rootfs ('/') since it's the only case where
1875 * mount_dir ends in '/'
1877 if (mount_dir_len == 1)
1878 mount_dir_len--;
1879 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1880 goto out;
1882 if (g_lstat (path, &statbuf) != 0)
1883 goto out;
1885 if (!(S_ISDIR (statbuf.st_mode) &&
1886 statbuf.st_uid == 0 &&
1887 statbuf.st_gid == 0))
1888 goto out;
1890 ret = TRUE;
1892 out:
1893 g_free (mount_dir);
1894 return ret;
1896 #endif
1898 static gboolean
1899 g_local_file_trash (GFile *file,
1900 GCancellable *cancellable,
1901 GError **error)
1903 GLocalFile *local = G_LOCAL_FILE (file);
1904 GStatBuf file_stat, home_stat;
1905 const char *homedir;
1906 char *trashdir, *topdir, *infodir, *filesdir;
1907 char *basename, *trashname, *trashfile, *infoname, *infofile;
1908 char *original_name, *original_name_escaped;
1909 int i;
1910 char *data;
1911 gboolean is_homedir_trash;
1912 char *delete_time = NULL;
1913 int fd;
1914 GStatBuf trash_stat, global_stat;
1915 char *dirname, *globaldir;
1916 GVfsClass *class;
1917 GVfs *vfs;
1918 int errsv;
1920 if (g_lstat (local->filename, &file_stat) != 0)
1922 errsv = errno;
1924 g_set_io_error (error,
1925 _("Error trashing file %s: %s"),
1926 file, errsv);
1927 return FALSE;
1930 homedir = g_get_home_dir ();
1931 g_stat (homedir, &home_stat);
1933 is_homedir_trash = FALSE;
1934 trashdir = NULL;
1935 if (file_stat.st_dev == home_stat.st_dev)
1937 is_homedir_trash = TRUE;
1938 errno = 0;
1939 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1940 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1942 char *display_name;
1943 errsv = errno;
1945 display_name = g_filename_display_name (trashdir);
1946 g_set_error (error, G_IO_ERROR,
1947 g_io_error_from_errno (errsv),
1948 _("Unable to create trash dir %s: %s"),
1949 display_name, g_strerror (errsv));
1950 g_free (display_name);
1951 g_free (trashdir);
1952 return FALSE;
1954 topdir = g_strdup (g_get_user_data_dir ());
1956 else
1958 uid_t uid;
1959 char uid_str[32];
1960 GUnixMountEntry *mount;
1962 uid = geteuid ();
1963 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1965 topdir = _g_local_file_find_topdir_for_internal (local->filename,
1966 file_stat.st_dev);
1967 if (topdir == NULL)
1969 g_set_io_error (error,
1970 _("Unable to find toplevel directory to trash %s"),
1971 file, ENOTSUP);
1972 return FALSE;
1975 mount = g_unix_mount_at (topdir, NULL);
1976 if (mount == NULL || g_unix_mount_is_system_internal (mount))
1978 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1979 _("Trashing on system internal mounts is not supported"));
1981 g_clear_pointer (&mount, g_unix_mount_free);
1982 g_free (topdir);
1984 return FALSE;
1987 g_clear_pointer (&mount, g_unix_mount_free);
1989 /* Try looking for global trash dir $topdir/.Trash/$uid */
1990 globaldir = g_build_filename (topdir, ".Trash", NULL);
1991 if (g_lstat (globaldir, &global_stat) == 0 &&
1992 S_ISDIR (global_stat.st_mode) &&
1993 (global_stat.st_mode & S_ISVTX) != 0)
1995 trashdir = g_build_filename (globaldir, uid_str, NULL);
1997 if (g_lstat (trashdir, &trash_stat) == 0)
1999 if (!S_ISDIR (trash_stat.st_mode) ||
2000 trash_stat.st_uid != uid)
2002 /* Not a directory or not owned by user, ignore */
2003 g_free (trashdir);
2004 trashdir = NULL;
2007 else if (g_mkdir (trashdir, 0700) == -1)
2009 g_free (trashdir);
2010 trashdir = NULL;
2013 g_free (globaldir);
2015 if (trashdir == NULL)
2017 gboolean tried_create;
2019 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2020 dirname = g_strdup_printf (".Trash-%s", uid_str);
2021 trashdir = g_build_filename (topdir, dirname, NULL);
2022 g_free (dirname);
2024 tried_create = FALSE;
2026 retry:
2027 if (g_lstat (trashdir, &trash_stat) == 0)
2029 if (!S_ISDIR (trash_stat.st_mode) ||
2030 trash_stat.st_uid != uid)
2032 /* Remove the failed directory */
2033 if (tried_create)
2034 g_remove (trashdir);
2036 /* Not a directory or not owned by user, ignore */
2037 g_free (trashdir);
2038 trashdir = NULL;
2041 else
2043 if (!tried_create &&
2044 g_mkdir (trashdir, 0700) != -1)
2046 /* Ensure that the created dir has the right uid etc.
2047 This might fail on e.g. a FAT dir */
2048 tried_create = TRUE;
2049 goto retry;
2051 else
2053 g_free (trashdir);
2054 trashdir = NULL;
2059 if (trashdir == NULL)
2061 g_free (topdir);
2062 g_set_io_error (error,
2063 _("Unable to find or create trash directory for %s"),
2064 file, G_IO_ERROR_NOT_SUPPORTED);
2065 return FALSE;
2069 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2071 infodir = g_build_filename (trashdir, "info", NULL);
2072 filesdir = g_build_filename (trashdir, "files", NULL);
2073 g_free (trashdir);
2075 /* Make sure we have the subdirectories */
2076 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2077 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2079 g_free (topdir);
2080 g_free (infodir);
2081 g_free (filesdir);
2082 g_set_io_error (error,
2083 _("Unable to find or create trash directory for %s"),
2084 file, G_IO_ERROR_NOT_SUPPORTED);
2085 return FALSE;
2088 basename = g_path_get_basename (local->filename);
2089 i = 1;
2090 trashname = NULL;
2091 infofile = NULL;
2092 do {
2093 g_free (trashname);
2094 g_free (infofile);
2096 trashname = get_unique_filename (basename, i++);
2097 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2098 infofile = g_build_filename (infodir, infoname, NULL);
2099 g_free (infoname);
2101 fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
2102 errsv = errno;
2103 } while (fd == -1 && errsv == EEXIST);
2105 g_free (basename);
2106 g_free (infodir);
2108 if (fd == -1)
2110 errsv = errno;
2112 g_free (filesdir);
2113 g_free (topdir);
2114 g_free (trashname);
2115 g_free (infofile);
2117 g_set_io_error (error,
2118 _("Unable to create trashing info file for %s: %s"),
2119 file, errsv);
2120 return FALSE;
2123 (void) g_close (fd, NULL);
2125 /* Write the full content of the info file before trashing to make
2126 * sure someone doesn't read an empty file. See #749314
2129 /* Use absolute names for homedir */
2130 if (is_homedir_trash)
2131 original_name = g_strdup (local->filename);
2132 else
2133 original_name = try_make_relative (local->filename, topdir);
2134 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2136 g_free (original_name);
2137 g_free (topdir);
2140 GDateTime *now = g_date_time_new_now_local ();
2141 if (now != NULL)
2142 delete_time = g_date_time_format (now, "%Y-%m-%dT%H:%M:%S");
2143 else
2144 delete_time = g_strdup ("9999-12-31T23:59:59");
2145 g_date_time_unref (now);
2148 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2149 original_name_escaped, delete_time);
2150 g_free (delete_time);
2152 g_file_set_contents (infofile, data, -1, NULL);
2154 /* TODO: Maybe we should verify that you can delete the file from the trash
2155 * before moving it? OTOH, that is hard, as it needs a recursive scan
2158 trashfile = g_build_filename (filesdir, trashname, NULL);
2160 g_free (filesdir);
2162 if (g_rename (local->filename, trashfile) == -1)
2164 errsv = errno;
2166 g_unlink (infofile);
2168 g_free (trashname);
2169 g_free (infofile);
2170 g_free (trashfile);
2172 if (errsv == EXDEV)
2173 /* The trash dir was actually on another fs anyway!?
2174 * This can happen when the same device is mounted multiple
2175 * times, or with bind mounts of the same fs.
2177 g_set_io_error (error,
2178 _("Unable to trash file %s across filesystem boundaries"),
2179 file, ENOTSUP);
2180 else
2181 g_set_io_error (error,
2182 _("Unable to trash file %s: %s"),
2183 file, errsv);
2184 return FALSE;
2187 vfs = g_vfs_get_default ();
2188 class = G_VFS_GET_CLASS (vfs);
2189 if (class->local_file_moved)
2190 class->local_file_moved (vfs, local->filename, trashfile);
2192 g_free (trashfile);
2194 /* TODO: Do we need to update mtime/atime here after the move? */
2196 g_free (infofile);
2197 g_free (data);
2199 g_free (original_name_escaped);
2200 g_free (trashname);
2202 return TRUE;
2204 #else /* G_OS_WIN32 */
2205 gboolean
2206 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2208 return FALSE; /* XXX ??? */
2211 static gboolean
2212 g_local_file_trash (GFile *file,
2213 GCancellable *cancellable,
2214 GError **error)
2216 GLocalFile *local = G_LOCAL_FILE (file);
2217 SHFILEOPSTRUCTW op = {0};
2218 gboolean success;
2219 wchar_t *wfilename;
2220 long len;
2222 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2223 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2224 wfilename = g_renew (wchar_t, wfilename, len + 2);
2225 wfilename[len + 1] = 0;
2227 op.wFunc = FO_DELETE;
2228 op.pFrom = wfilename;
2229 op.fFlags = FOF_ALLOWUNDO;
2231 success = SHFileOperationW (&op) == 0;
2233 if (success && op.fAnyOperationsAborted)
2235 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2236 g_cancellable_cancel (cancellable);
2237 g_set_io_error (error,
2238 _("Unable to trash file %s: %s"),
2239 file, ECANCELED);
2240 success = FALSE;
2242 else if (!success)
2243 g_set_io_error (error,
2244 _("Unable to trash file %s"),
2245 file, 0);
2247 g_free (wfilename);
2248 return success;
2250 #endif /* G_OS_WIN32 */
2252 static gboolean
2253 g_local_file_make_directory (GFile *file,
2254 GCancellable *cancellable,
2255 GError **error)
2257 GLocalFile *local = G_LOCAL_FILE (file);
2259 if (g_mkdir (local->filename, 0777) == -1)
2261 int errsv = errno;
2263 if (errsv == EINVAL)
2264 /* This must be an invalid filename, on e.g. FAT */
2265 g_set_error_literal (error, G_IO_ERROR,
2266 G_IO_ERROR_INVALID_FILENAME,
2267 _("Invalid filename"));
2268 else
2269 g_set_io_error (error,
2270 _("Error creating directory %s: %s"),
2271 file, errsv);
2272 return FALSE;
2275 return TRUE;
2278 static gboolean
2279 g_local_file_make_symbolic_link (GFile *file,
2280 const char *symlink_value,
2281 GCancellable *cancellable,
2282 GError **error)
2284 #ifdef HAVE_SYMLINK
2285 GLocalFile *local = G_LOCAL_FILE (file);
2287 if (symlink (symlink_value, local->filename) == -1)
2289 int errsv = errno;
2291 if (errsv == EINVAL)
2292 /* This must be an invalid filename, on e.g. FAT */
2293 g_set_error_literal (error, G_IO_ERROR,
2294 G_IO_ERROR_INVALID_FILENAME,
2295 _("Invalid filename"));
2296 else if (errsv == EPERM)
2297 g_set_error (error, G_IO_ERROR,
2298 G_IO_ERROR_NOT_SUPPORTED,
2299 _("Filesystem does not support symbolic links"));
2300 else
2301 g_set_io_error (error,
2302 _("Error making symbolic link %s: %s"),
2303 file, errsv);
2304 return FALSE;
2306 return TRUE;
2307 #else
2308 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Symbolic links not supported"));
2309 return FALSE;
2310 #endif
2314 static gboolean
2315 g_local_file_copy (GFile *source,
2316 GFile *destination,
2317 GFileCopyFlags flags,
2318 GCancellable *cancellable,
2319 GFileProgressCallback progress_callback,
2320 gpointer progress_callback_data,
2321 GError **error)
2323 /* Fall back to default copy */
2324 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2325 return FALSE;
2328 static gboolean
2329 g_local_file_move (GFile *source,
2330 GFile *destination,
2331 GFileCopyFlags flags,
2332 GCancellable *cancellable,
2333 GFileProgressCallback progress_callback,
2334 gpointer progress_callback_data,
2335 GError **error)
2337 GLocalFile *local_source, *local_destination;
2338 GStatBuf statbuf;
2339 gboolean destination_exist, source_is_dir;
2340 char *backup_name;
2341 int res;
2342 off_t source_size;
2343 GVfsClass *class;
2344 GVfs *vfs;
2346 if (!G_IS_LOCAL_FILE (source) ||
2347 !G_IS_LOCAL_FILE (destination))
2349 /* Fall back to default move */
2350 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2351 return FALSE;
2354 local_source = G_LOCAL_FILE (source);
2355 local_destination = G_LOCAL_FILE (destination);
2357 res = g_lstat (local_source->filename, &statbuf);
2358 if (res == -1)
2360 int errsv = errno;
2362 g_set_io_error (error,
2363 _("Error moving file %s: %s"),
2364 source, errsv);
2365 return FALSE;
2368 source_is_dir = S_ISDIR (statbuf.st_mode);
2369 source_size = statbuf.st_size;
2371 destination_exist = FALSE;
2372 res = g_lstat (local_destination->filename, &statbuf);
2373 if (res == 0)
2375 destination_exist = TRUE; /* Target file exists */
2377 if (flags & G_FILE_COPY_OVERWRITE)
2379 /* Always fail on dirs, even with overwrite */
2380 if (S_ISDIR (statbuf.st_mode))
2382 if (source_is_dir)
2383 g_set_error_literal (error,
2384 G_IO_ERROR,
2385 G_IO_ERROR_WOULD_MERGE,
2386 _("Can’t move directory over directory"));
2387 else
2388 g_set_error_literal (error,
2389 G_IO_ERROR,
2390 G_IO_ERROR_IS_DIRECTORY,
2391 _("Can’t copy over directory"));
2392 return FALSE;
2395 else
2397 g_set_io_error (error,
2398 _("Error moving file %s: %s"),
2399 source, EEXIST);
2400 return FALSE;
2404 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2406 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2407 if (g_rename (local_destination->filename, backup_name) == -1)
2409 g_set_error_literal (error,
2410 G_IO_ERROR,
2411 G_IO_ERROR_CANT_CREATE_BACKUP,
2412 _("Backup file creation failed"));
2413 g_free (backup_name);
2414 return FALSE;
2416 g_free (backup_name);
2417 destination_exist = FALSE; /* It did, but no more */
2420 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2422 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2423 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2424 res = g_unlink (local_destination->filename);
2425 if (res == -1)
2427 int errsv = errno;
2429 g_set_error (error, G_IO_ERROR,
2430 g_io_error_from_errno (errsv),
2431 _("Error removing target file: %s"),
2432 g_strerror (errsv));
2433 return FALSE;
2437 if (g_rename (local_source->filename, local_destination->filename) == -1)
2439 int errsv = errno;
2441 if (errsv == EXDEV)
2442 /* This will cause the fallback code to run */
2443 g_set_error_literal (error, G_IO_ERROR,
2444 G_IO_ERROR_NOT_SUPPORTED,
2445 _("Move between mounts not supported"));
2446 else if (errsv == EINVAL)
2447 /* This must be an invalid filename, on e.g. FAT, or
2448 we're trying to move the file into itself...
2449 We return invalid filename for both... */
2450 g_set_error_literal (error, G_IO_ERROR,
2451 G_IO_ERROR_INVALID_FILENAME,
2452 _("Invalid filename"));
2453 else
2454 g_set_io_error (error,
2455 _("Error moving file %s: %s"),
2456 source, errsv);
2457 return FALSE;
2460 vfs = g_vfs_get_default ();
2461 class = G_VFS_GET_CLASS (vfs);
2462 if (class->local_file_moved)
2463 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2465 /* Make sure we send full copied size */
2466 if (progress_callback)
2467 progress_callback (source_size, source_size, progress_callback_data);
2469 return TRUE;
2472 #ifdef G_OS_WIN32
2474 gboolean
2475 g_local_file_is_remote (const gchar *filename)
2477 return FALSE;
2480 #else
2482 static gboolean
2483 is_remote_fs (const gchar *filename)
2485 const char *fsname = NULL;
2487 #ifdef USE_STATFS
2488 struct statfs statfs_buffer;
2489 int statfs_result = 0;
2491 #if STATFS_ARGS == 2
2492 statfs_result = statfs (filename, &statfs_buffer);
2493 #elif STATFS_ARGS == 4
2494 statfs_result = statfs (filename, &statfs_buffer, sizeof (statfs_buffer), 0);
2495 #endif
2497 #elif defined(USE_STATVFS)
2498 struct statvfs statfs_buffer;
2499 int statfs_result = 0;
2501 statfs_result = statvfs (filename, &statfs_buffer);
2502 #else
2503 return FALSE;
2504 #endif
2506 if (statfs_result == -1)
2507 return FALSE;
2509 #ifdef USE_STATFS
2510 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
2511 fsname = statfs_buffer.f_fstypename;
2512 #else
2513 fsname = get_fs_type (statfs_buffer.f_type);
2514 #endif
2516 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
2517 fsname = statfs_buffer.f_basetype;
2518 #endif
2520 if (fsname != NULL)
2522 if (strcmp (fsname, "nfs") == 0)
2523 return TRUE;
2524 if (strcmp (fsname, "nfs4") == 0)
2525 return TRUE;
2528 return FALSE;
2531 gboolean
2532 g_local_file_is_remote (const gchar *filename)
2534 static gboolean remote_home;
2535 static gsize initialized;
2536 const gchar *home;
2538 home = g_get_home_dir ();
2539 if (path_has_prefix (filename, home))
2541 if (g_once_init_enter (&initialized))
2543 remote_home = is_remote_fs (home);
2544 g_once_init_leave (&initialized, TRUE);
2546 return remote_home;
2549 return FALSE;
2551 #endif /* !G_OS_WIN32 */
2553 static GFileMonitor*
2554 g_local_file_monitor_dir (GFile *file,
2555 GFileMonitorFlags flags,
2556 GCancellable *cancellable,
2557 GError **error)
2559 GLocalFile *local_file = G_LOCAL_FILE (file);
2561 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2564 static GFileMonitor*
2565 g_local_file_monitor_file (GFile *file,
2566 GFileMonitorFlags flags,
2567 GCancellable *cancellable,
2568 GError **error)
2570 GLocalFile *local_file = G_LOCAL_FILE (file);
2572 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2575 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2577 * If available, we use fopenat() in preference to filenames for
2578 * efficiency and safety reasons. We know that fopenat() is available
2579 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2580 * defined as a macro.
2582 * We use a linked list of stack-allocated GSList nodes in order to be
2583 * able to reconstruct the filename for error messages. We actually
2584 * pass the filename to operate on through the top node of the list.
2586 * In case we're using openat(), this top filename will be a basename
2587 * which should be opened in the directory which has also had its fd
2588 * passed along. If we're not using openat() then it will be a full
2589 * absolute filename.
2592 static gboolean
2593 g_local_file_measure_size_error (GFileMeasureFlags flags,
2594 gint saved_errno,
2595 GSList *name,
2596 GError **error)
2598 /* Only report an error if we were at the toplevel or if the caller
2599 * requested reporting of all errors.
2601 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2603 GString *filename;
2604 GSList *node;
2606 /* Skip some work if there is no error return */
2607 if (!error)
2608 return FALSE;
2610 #ifdef AT_FDCWD
2611 /* If using openat() we need to rebuild the filename for the message */
2612 filename = g_string_new (name->data);
2613 for (node = name->next; node; node = node->next)
2615 gchar *utf8;
2617 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2618 utf8 = g_filename_display_name (node->data);
2619 g_string_prepend (filename, utf8);
2620 g_free (utf8);
2622 #else
2624 gchar *utf8;
2626 /* Otherwise, we already have it, so just use it. */
2627 node = name;
2628 filename = g_string_new (NULL);
2629 utf8 = g_filename_display_name (node->data);
2630 g_string_append (filename, utf8);
2631 g_free (utf8);
2633 #endif
2635 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2636 _("Could not determine the disk usage of %s: %s"),
2637 filename->str, g_strerror (saved_errno));
2639 g_string_free (filename, TRUE);
2641 return FALSE;
2644 else
2645 /* We're not reporting this error... */
2646 return TRUE;
2649 typedef struct
2651 GFileMeasureFlags flags;
2652 dev_t contained_on;
2653 GCancellable *cancellable;
2655 GFileMeasureProgressCallback progress_callback;
2656 gpointer progress_data;
2658 guint64 disk_usage;
2659 guint64 num_dirs;
2660 guint64 num_files;
2662 guint64 last_progress_report;
2663 } MeasureState;
2665 static gboolean
2666 g_local_file_measure_size_of_contents (gint fd,
2667 GSList *dir_name,
2668 MeasureState *state,
2669 GError **error);
2671 static gboolean
2672 g_local_file_measure_size_of_file (gint parent_fd,
2673 GSList *name,
2674 MeasureState *state,
2675 GError **error)
2677 GLocalFileStat buf;
2679 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2680 return FALSE;
2682 #if defined (AT_FDCWD)
2683 if (fstatat (parent_fd, name->data, &buf, AT_SYMLINK_NOFOLLOW) != 0)
2685 int errsv = errno;
2686 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2688 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2689 if (g_lstat (name->data, &buf) != 0)
2691 int errsv = errno;
2692 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2694 #else /* !AT_FDCWD && !HAVE_LSTAT && G_OS_WIN32 */
2695 if (GLIB_PRIVATE_CALL (g_win32_lstat_utf8) (name->data, &buf) != 0)
2697 int errsv = errno;
2698 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2700 #endif
2702 if (name->next)
2704 /* If not at the toplevel, check for a device boundary. */
2706 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2707 if (state->contained_on != buf.st_dev)
2708 return TRUE;
2710 else
2712 /* If, however, this is the toplevel, set the device number so
2713 * that recursive invocations can compare against it.
2715 state->contained_on = buf.st_dev;
2718 #if defined (G_OS_WIN32)
2719 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2720 state->disk_usage += buf.allocated_size;
2721 else
2722 #elif defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2723 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2724 state->disk_usage += buf.st_blocks * G_GUINT64_CONSTANT (512);
2725 else
2726 #endif
2727 state->disk_usage += buf.st_size;
2729 if (S_ISDIR (buf.st_mode))
2730 state->num_dirs++;
2731 else
2732 state->num_files++;
2734 if (state->progress_callback)
2736 /* We could attempt to do some cleverness here in order to avoid
2737 * calling clock_gettime() so much, but we're doing stats and opens
2738 * all over the place already...
2740 if (state->last_progress_report)
2742 guint64 now;
2744 now = g_get_monotonic_time ();
2746 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2748 (* state->progress_callback) (TRUE,
2749 state->disk_usage, state->num_dirs, state->num_files,
2750 state->progress_data);
2751 state->last_progress_report = now;
2754 else
2756 /* We must do an initial report to inform that more reports
2757 * will be coming.
2759 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2760 state->last_progress_report = g_get_monotonic_time ();
2764 if (S_ISDIR (buf.st_mode))
2766 int dir_fd = -1;
2767 #ifdef AT_FDCWD
2768 int errsv;
2769 #endif
2771 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2772 return FALSE;
2774 #ifdef AT_FDCWD
2775 #ifdef HAVE_OPEN_O_DIRECTORY
2776 dir_fd = openat (parent_fd, name->data, O_RDONLY|O_DIRECTORY);
2777 #else
2778 dir_fd = openat (parent_fd, name->data, O_RDONLY);
2779 #endif
2780 errsv = errno;
2781 if (dir_fd < 0)
2782 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2783 #endif
2785 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2786 return FALSE;
2789 return TRUE;
2792 static gboolean
2793 g_local_file_measure_size_of_contents (gint fd,
2794 GSList *dir_name,
2795 MeasureState *state,
2796 GError **error)
2798 gboolean success = TRUE;
2799 const gchar *name;
2800 GDir *dir;
2802 #ifdef AT_FDCWD
2804 /* If this fails, we want to preserve the errno from fopendir() */
2805 DIR *dirp;
2806 dirp = fdopendir (fd);
2807 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2809 #else
2810 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2811 #endif
2813 if (dir == NULL)
2815 gint saved_errno = errno;
2817 #ifdef AT_FDCWD
2818 close (fd);
2819 #endif
2821 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2824 while (success && (name = g_dir_read_name (dir)))
2826 GSList node;
2828 node.next = dir_name;
2829 #ifdef AT_FDCWD
2830 node.data = (gchar *) name;
2831 #else
2832 node.data = g_build_filename (dir_name->data, name, NULL);
2833 #endif
2835 success = g_local_file_measure_size_of_file (fd, &node, state, error);
2837 #ifndef AT_FDCWD
2838 g_free (node.data);
2839 #endif
2842 g_dir_close (dir);
2844 return success;
2847 static gboolean
2848 g_local_file_measure_disk_usage (GFile *file,
2849 GFileMeasureFlags flags,
2850 GCancellable *cancellable,
2851 GFileMeasureProgressCallback progress_callback,
2852 gpointer progress_data,
2853 guint64 *disk_usage,
2854 guint64 *num_dirs,
2855 guint64 *num_files,
2856 GError **error)
2858 GLocalFile *local_file = G_LOCAL_FILE (file);
2859 MeasureState state = { 0, };
2860 gint root_fd = -1;
2861 GSList node;
2863 state.flags = flags;
2864 state.cancellable = cancellable;
2865 state.progress_callback = progress_callback;
2866 state.progress_data = progress_data;
2868 #ifdef AT_FDCWD
2869 root_fd = AT_FDCWD;
2870 #endif
2872 node.data = local_file->filename;
2873 node.next = NULL;
2875 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
2876 return FALSE;
2878 if (disk_usage)
2879 *disk_usage = state.disk_usage;
2881 if (num_dirs)
2882 *num_dirs = state.num_dirs;
2884 if (num_files)
2885 *num_files = state.num_files;
2887 return TRUE;
2890 static void
2891 g_local_file_file_iface_init (GFileIface *iface)
2893 iface->dup = g_local_file_dup;
2894 iface->hash = g_local_file_hash;
2895 iface->equal = g_local_file_equal;
2896 iface->is_native = g_local_file_is_native;
2897 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2898 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2899 iface->get_basename = g_local_file_get_basename;
2900 iface->get_path = g_local_file_get_path;
2901 iface->get_uri = g_local_file_get_uri;
2902 iface->get_parse_name = g_local_file_get_parse_name;
2903 iface->get_parent = g_local_file_get_parent;
2904 iface->prefix_matches = g_local_file_prefix_matches;
2905 iface->get_relative_path = g_local_file_get_relative_path;
2906 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2907 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2908 iface->set_display_name = g_local_file_set_display_name;
2909 iface->enumerate_children = g_local_file_enumerate_children;
2910 iface->query_info = g_local_file_query_info;
2911 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2912 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2913 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2914 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2915 iface->set_attribute = g_local_file_set_attribute;
2916 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2917 iface->read_fn = g_local_file_read;
2918 iface->append_to = g_local_file_append_to;
2919 iface->create = g_local_file_create;
2920 iface->replace = g_local_file_replace;
2921 iface->open_readwrite = g_local_file_open_readwrite;
2922 iface->create_readwrite = g_local_file_create_readwrite;
2923 iface->replace_readwrite = g_local_file_replace_readwrite;
2924 iface->delete_file = g_local_file_delete;
2925 iface->trash = g_local_file_trash;
2926 iface->make_directory = g_local_file_make_directory;
2927 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2928 iface->copy = g_local_file_copy;
2929 iface->move = g_local_file_move;
2930 iface->monitor_dir = g_local_file_monitor_dir;
2931 iface->monitor_file = g_local_file_monitor_file;
2932 iface->measure_disk_usage = g_local_file_measure_disk_usage;
2934 iface->supports_thread_contexts = TRUE;