2.54.2
[glib.git] / gio / glocalfile.c
blobd417c4991c442a45093cd2f68ca97c6ec9f1f722
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 "glibintl.h"
66 #ifdef G_OS_UNIX
67 #include "glib-unix.h"
68 #endif
69 #include "glib-private.h"
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 static char *
203 canonicalize_filename (const char *filename)
205 char *canon, *start, *p, *q;
206 char *cwd;
207 int i;
209 if (!g_path_is_absolute (filename))
211 cwd = g_get_current_dir ();
212 canon = g_build_filename (cwd, filename, NULL);
213 g_free (cwd);
215 else
216 canon = g_strdup (filename);
218 start = (char *)g_path_skip_root (canon);
220 if (start == NULL)
222 /* This shouldn't really happen, as g_get_current_dir() should
223 return an absolute pathname, but bug 573843 shows this is
224 not always happening */
225 g_free (canon);
226 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
229 /* POSIX allows double slashes at the start to
230 * mean something special (as does windows too).
231 * So, "//" != "/", but more than two slashes
232 * is treated as "/".
234 i = 0;
235 for (p = start - 1;
236 (p >= canon) &&
237 G_IS_DIR_SEPARATOR (*p);
238 p--)
239 i++;
240 if (i > 2)
242 i -= 1;
243 start -= i;
244 memmove (start, start+i, strlen (start+i)+1);
247 /* Make sure we're using the canonical dir separator */
248 p++;
249 while (p < start && G_IS_DIR_SEPARATOR (*p))
250 *p++ = G_DIR_SEPARATOR;
252 p = start;
253 while (*p != 0)
255 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
257 memmove (p, p+1, strlen (p+1)+1);
259 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
261 q = p + 2;
262 /* Skip previous separator */
263 p = p - 2;
264 if (p < start)
265 p = start;
266 while (p > start && !G_IS_DIR_SEPARATOR (*p))
267 p--;
268 if (G_IS_DIR_SEPARATOR (*p))
269 *p++ = G_DIR_SEPARATOR;
270 memmove (p, q, strlen (q)+1);
272 else
274 /* Skip until next separator */
275 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
276 p++;
278 if (*p != 0)
280 /* Canonicalize one separator */
281 *p++ = G_DIR_SEPARATOR;
285 /* Remove additional separators */
286 q = p;
287 while (*q && G_IS_DIR_SEPARATOR (*q))
288 q++;
290 if (p != q)
291 memmove (p, q, strlen (q)+1);
294 /* Remove trailing slashes */
295 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
296 *(p-1) = 0;
298 return canon;
301 GFile *
302 _g_local_file_new (const char *filename)
304 GLocalFile *local;
306 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
307 local->filename = canonicalize_filename (filename);
309 return G_FILE (local);
312 /*< internal >
313 * g_local_file_new_from_dirname_and_basename:
314 * @dirname: an absolute, canonical directory name
315 * @basename: the name of a child inside @dirname
317 * Creates a #GFile from @dirname and @basename.
319 * This is more efficient than pasting the fields together for yourself
320 * and creating a #GFile from the result, and also more efficient than
321 * creating a #GFile for the dirname and using g_file_get_child().
323 * @dirname must be canonical, as per GLocalFile's opinion of what
324 * canonical means. This means that you should only pass strings that
325 * were returned by _g_local_file_get_filename().
327 * Returns: a #GFile
329 GFile *
330 g_local_file_new_from_dirname_and_basename (const gchar *dirname,
331 const gchar *basename)
333 GLocalFile *local;
335 g_return_val_if_fail (dirname != NULL, NULL);
336 g_return_val_if_fail (basename && basename[0] && !strchr (basename, '/'), NULL);
338 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
339 local->filename = g_build_filename (dirname, basename, NULL);
341 return G_FILE (local);
344 static gboolean
345 g_local_file_is_native (GFile *file)
347 return TRUE;
350 static gboolean
351 g_local_file_has_uri_scheme (GFile *file,
352 const char *uri_scheme)
354 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
357 static char *
358 g_local_file_get_uri_scheme (GFile *file)
360 return g_strdup ("file");
363 static char *
364 g_local_file_get_basename (GFile *file)
366 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
369 static char *
370 g_local_file_get_path (GFile *file)
372 return g_strdup (G_LOCAL_FILE (file)->filename);
375 static char *
376 g_local_file_get_uri (GFile *file)
378 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
381 static gboolean
382 get_filename_charset (const gchar **filename_charset)
384 const gchar **charsets;
385 gboolean is_utf8;
387 is_utf8 = g_get_filename_charsets (&charsets);
389 if (filename_charset)
390 *filename_charset = charsets[0];
392 return is_utf8;
395 static gboolean
396 name_is_valid_for_display (const char *string,
397 gboolean is_valid_utf8)
399 char c;
401 if (!is_valid_utf8 &&
402 !g_utf8_validate (string, -1, NULL))
403 return FALSE;
405 while ((c = *string++) != 0)
407 if (g_ascii_iscntrl (c))
408 return FALSE;
411 return TRUE;
414 static char *
415 g_local_file_get_parse_name (GFile *file)
417 const char *filename;
418 char *parse_name;
419 const gchar *charset;
420 char *utf8_filename;
421 char *roundtripped_filename;
422 gboolean free_utf8_filename;
423 gboolean is_valid_utf8;
424 char *escaped_path;
426 filename = G_LOCAL_FILE (file)->filename;
427 if (get_filename_charset (&charset))
429 utf8_filename = (char *)filename;
430 free_utf8_filename = FALSE;
431 is_valid_utf8 = FALSE; /* Can't guarantee this */
433 else
435 utf8_filename = g_convert (filename, -1,
436 "UTF-8", charset, NULL, NULL, NULL);
437 free_utf8_filename = TRUE;
438 is_valid_utf8 = TRUE;
440 if (utf8_filename != NULL)
442 /* Make sure we can roundtrip: */
443 roundtripped_filename = g_convert (utf8_filename, -1,
444 charset, "UTF-8", NULL, NULL, NULL);
446 if (roundtripped_filename == NULL ||
447 strcmp (filename, roundtripped_filename) != 0)
449 g_free (utf8_filename);
450 utf8_filename = NULL;
453 g_free (roundtripped_filename);
457 if (utf8_filename != NULL &&
458 name_is_valid_for_display (utf8_filename, is_valid_utf8))
460 if (free_utf8_filename)
461 parse_name = utf8_filename;
462 else
463 parse_name = g_strdup (utf8_filename);
465 else
467 #ifdef G_OS_WIN32
468 char *dup_filename, *p, *backslash;
470 /* Turn backslashes into forward slashes like
471 * g_filename_to_uri() would do (but we can't use that because
472 * it doesn't output IRIs).
474 dup_filename = g_strdup (filename);
475 filename = p = dup_filename;
477 while ((backslash = strchr (p, '\\')) != NULL)
479 *backslash = '/';
480 p = backslash + 1;
482 #endif
484 escaped_path = g_uri_escape_string (filename,
485 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
486 TRUE);
487 parse_name = g_strconcat ("file://",
488 (*escaped_path != '/') ? "/" : "",
489 escaped_path,
490 NULL);
492 g_free (escaped_path);
493 #ifdef G_OS_WIN32
494 g_free (dup_filename);
495 #endif
496 if (free_utf8_filename)
497 g_free (utf8_filename);
500 return parse_name;
503 static GFile *
504 g_local_file_get_parent (GFile *file)
506 GLocalFile *local = G_LOCAL_FILE (file);
507 const char *non_root;
508 char *dirname;
509 GFile *parent;
511 /* Check for root; local->filename is guaranteed to be absolute, so
512 * g_path_skip_root() should never return NULL. */
513 non_root = g_path_skip_root (local->filename);
514 g_assert (non_root != NULL);
516 if (*non_root == 0)
517 return NULL;
519 dirname = g_path_get_dirname (local->filename);
520 parent = _g_local_file_new (dirname);
521 g_free (dirname);
522 return parent;
525 static GFile *
526 g_local_file_dup (GFile *file)
528 GLocalFile *local = G_LOCAL_FILE (file);
530 return _g_local_file_new (local->filename);
533 static guint
534 g_local_file_hash (GFile *file)
536 GLocalFile *local = G_LOCAL_FILE (file);
538 return g_str_hash (local->filename);
541 static gboolean
542 g_local_file_equal (GFile *file1,
543 GFile *file2)
545 GLocalFile *local1 = G_LOCAL_FILE (file1);
546 GLocalFile *local2 = G_LOCAL_FILE (file2);
548 return g_str_equal (local1->filename, local2->filename);
551 static const char *
552 match_prefix (const char *path,
553 const char *prefix)
555 int prefix_len;
557 prefix_len = strlen (prefix);
558 if (strncmp (path, prefix, prefix_len) != 0)
559 return NULL;
561 /* Handle the case where prefix is the root, so that
562 * the IS_DIR_SEPRARATOR check below works */
563 if (prefix_len > 0 &&
564 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
565 prefix_len--;
567 return path + prefix_len;
570 static gboolean
571 g_local_file_prefix_matches (GFile *parent,
572 GFile *descendant)
574 GLocalFile *parent_local = G_LOCAL_FILE (parent);
575 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
576 const char *remainder;
578 remainder = match_prefix (descendant_local->filename, parent_local->filename);
579 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
580 return TRUE;
581 return FALSE;
584 static char *
585 g_local_file_get_relative_path (GFile *parent,
586 GFile *descendant)
588 GLocalFile *parent_local = G_LOCAL_FILE (parent);
589 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
590 const char *remainder;
592 remainder = match_prefix (descendant_local->filename, parent_local->filename);
594 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
595 return g_strdup (remainder + 1);
596 return NULL;
599 static GFile *
600 g_local_file_resolve_relative_path (GFile *file,
601 const char *relative_path)
603 GLocalFile *local = G_LOCAL_FILE (file);
604 char *filename;
605 GFile *child;
607 if (g_path_is_absolute (relative_path))
608 return _g_local_file_new (relative_path);
610 filename = g_build_filename (local->filename, relative_path, NULL);
611 child = _g_local_file_new (filename);
612 g_free (filename);
614 return child;
617 static GFileEnumerator *
618 g_local_file_enumerate_children (GFile *file,
619 const char *attributes,
620 GFileQueryInfoFlags flags,
621 GCancellable *cancellable,
622 GError **error)
624 GLocalFile *local = G_LOCAL_FILE (file);
625 return _g_local_file_enumerator_new (local,
626 attributes, flags,
627 cancellable, error);
630 static GFile *
631 g_local_file_get_child_for_display_name (GFile *file,
632 const char *display_name,
633 GError **error)
635 GFile *new_file;
636 char *basename;
638 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
639 if (basename == NULL)
641 g_set_error (error, G_IO_ERROR,
642 G_IO_ERROR_INVALID_FILENAME,
643 _("Invalid filename %s"), display_name);
644 return NULL;
647 new_file = g_file_get_child (file, basename);
648 g_free (basename);
650 return new_file;
653 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
654 static const char *
655 get_fs_type (long f_type)
657 /* filesystem ids taken from linux manpage */
658 switch (f_type)
660 case 0xadf5:
661 return "adfs";
662 case 0x5346414f:
663 return "afs";
664 case 0x0187:
665 return "autofs";
666 case 0xADFF:
667 return "affs";
668 case 0x42465331:
669 return "befs";
670 case 0x1BADFACE:
671 return "bfs";
672 case 0x9123683E:
673 return "btrfs";
674 case 0xFF534D42:
675 return "cifs";
676 case 0x73757245:
677 return "coda";
678 case 0x012FF7B7:
679 return "coh";
680 case 0x28cd3d45:
681 return "cramfs";
682 case 0x1373:
683 return "devfs";
684 case 0x00414A53:
685 return "efs";
686 case 0x137D:
687 return "ext";
688 case 0xEF51:
689 return "ext2";
690 case 0xEF53:
691 return "ext3/ext4";
692 case 0x4244:
693 return "hfs";
694 case 0xF995E849:
695 return "hpfs";
696 case 0x958458f6:
697 return "hugetlbfs";
698 case 0x9660:
699 return "isofs";
700 case 0x72b6:
701 return "jffs2";
702 case 0x3153464a:
703 return "jfs";
704 case 0x137F:
705 return "minix";
706 case 0x138F:
707 return "minix2";
708 case 0x2468:
709 return "minix2";
710 case 0x2478:
711 return "minix22";
712 case 0x4d44:
713 return "msdos";
714 case 0x564c:
715 return "ncp";
716 case 0x6969:
717 return "nfs";
718 case 0x5346544e:
719 return "ntfs";
720 case 0x9fa1:
721 return "openprom";
722 case 0x9fa0:
723 return "proc";
724 case 0x002f:
725 return "qnx4";
726 case 0x52654973:
727 return "reiserfs";
728 case 0x7275:
729 return "romfs";
730 case 0x517B:
731 return "smb";
732 case 0x73717368:
733 return "squashfs";
734 case 0x012FF7B6:
735 return "sysv2";
736 case 0x012FF7B5:
737 return "sysv4";
738 case 0x01021994:
739 return "tmpfs";
740 case 0x15013346:
741 return "udf";
742 case 0x00011954:
743 return "ufs";
744 case 0x9fa2:
745 return "usbdevice";
746 case 0xa501FCF5:
747 return "vxfs";
748 case 0x012FF7B4:
749 return "xenix";
750 case 0x58465342:
751 return "xfs";
752 case 0x012FD16D:
753 return "xiafs";
754 case 0x52345362:
755 return "reiser4";
756 default:
757 return NULL;
760 #endif
762 #ifndef G_OS_WIN32
764 G_LOCK_DEFINE_STATIC(mount_info_hash);
765 static GHashTable *mount_info_hash = NULL;
766 static guint64 mount_info_hash_cache_time = 0;
768 typedef enum {
769 MOUNT_INFO_READONLY = 1<<0
770 } MountInfo;
772 static gboolean
773 device_equal (gconstpointer v1,
774 gconstpointer v2)
776 return *(dev_t *)v1 == *(dev_t *)v2;
779 static guint
780 device_hash (gconstpointer v)
782 return (guint) *(dev_t *)v;
785 static void
786 get_mount_info (GFileInfo *fs_info,
787 const char *path,
788 GFileAttributeMatcher *matcher)
790 GStatBuf buf;
791 gboolean got_info;
792 gpointer info_as_ptr;
793 guint mount_info;
794 char *mountpoint;
795 dev_t *dev;
796 GUnixMountEntry *mount;
797 guint64 cache_time;
799 if (g_lstat (path, &buf) != 0)
800 return;
802 G_LOCK (mount_info_hash);
804 if (mount_info_hash == NULL)
805 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
806 g_free, NULL);
809 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
810 g_hash_table_remove_all (mount_info_hash);
812 got_info = g_hash_table_lookup_extended (mount_info_hash,
813 &buf.st_dev,
814 NULL,
815 &info_as_ptr);
817 G_UNLOCK (mount_info_hash);
819 mount_info = GPOINTER_TO_UINT (info_as_ptr);
821 if (!got_info)
823 mount_info = 0;
825 mountpoint = find_mountpoint_for (path, buf.st_dev);
826 if (mountpoint == NULL)
827 mountpoint = g_strdup ("/");
829 mount = g_unix_mount_at (mountpoint, &cache_time);
830 if (mount)
832 if (g_unix_mount_is_readonly (mount))
833 mount_info |= MOUNT_INFO_READONLY;
835 g_unix_mount_free (mount);
838 g_free (mountpoint);
840 dev = g_new0 (dev_t, 1);
841 *dev = buf.st_dev;
843 G_LOCK (mount_info_hash);
844 mount_info_hash_cache_time = cache_time;
845 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
846 G_UNLOCK (mount_info_hash);
849 if (mount_info & MOUNT_INFO_READONLY)
850 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
853 #endif
855 #ifdef G_OS_WIN32
857 static gboolean
858 is_xp_or_later (void)
860 static int result = -1;
862 if (result == -1)
864 #ifndef _MSC_VER
865 OSVERSIONINFOEX ver_info = {0};
866 DWORDLONG cond_mask = 0;
867 int op = VER_GREATER_EQUAL;
869 ver_info.dwOSVersionInfoSize = sizeof ver_info;
870 ver_info.dwMajorVersion = 5;
871 ver_info.dwMinorVersion = 1;
873 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
874 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
876 result = VerifyVersionInfo (&ver_info,
877 VER_MAJORVERSION | VER_MINORVERSION,
878 cond_mask) != 0;
879 #else
880 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
881 #endif
884 return result;
887 static wchar_t *
888 get_volume_for_path (const char *path)
890 long len;
891 wchar_t *wpath;
892 wchar_t *result;
894 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
895 result = g_new (wchar_t, MAX_PATH);
897 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
899 char *msg = g_win32_error_message (GetLastError ());
900 g_critical ("GetVolumePathName failed: %s", msg);
901 g_free (msg);
902 g_free (result);
903 g_free (wpath);
904 return NULL;
907 len = wcslen (result);
908 if (len > 0 && result[len-1] != L'\\')
910 result = g_renew (wchar_t, result, len + 2);
911 result[len] = L'\\';
912 result[len + 1] = 0;
915 g_free (wpath);
916 return result;
919 static char *
920 find_mountpoint_for (const char *file, dev_t dev)
922 wchar_t *wpath;
923 char *utf8_path;
925 wpath = get_volume_for_path (file);
926 if (!wpath)
927 return NULL;
929 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
931 g_free (wpath);
932 return utf8_path;
935 static void
936 get_filesystem_readonly (GFileInfo *info,
937 const char *path)
939 wchar_t *rootdir;
941 rootdir = get_volume_for_path (path);
943 if (rootdir)
945 if (is_xp_or_later ())
947 DWORD flags;
948 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
949 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
950 (flags & FILE_READ_ONLY_VOLUME) != 0);
952 else
954 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
955 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
959 g_free (rootdir);
962 #endif /* G_OS_WIN32 */
964 #pragma GCC diagnostic push
965 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
966 static void
967 g_set_io_error (GError **error,
968 const gchar *msg,
969 GFile *file,
970 gint errsv)
972 GLocalFile *local = G_LOCAL_FILE (file);
973 gchar *display_name;
975 display_name = g_filename_display_name (local->filename);
976 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
977 msg, display_name, g_strerror (errsv));
978 g_free (display_name);
980 #pragma GCC diagnostic pop
982 static GFileInfo *
983 g_local_file_query_filesystem_info (GFile *file,
984 const char *attributes,
985 GCancellable *cancellable,
986 GError **error)
988 GLocalFile *local = G_LOCAL_FILE (file);
989 GFileInfo *info;
990 int statfs_result = 0;
991 gboolean no_size;
992 #ifndef G_OS_WIN32
993 const char *fstype;
994 #ifdef USE_STATFS
995 guint64 block_size;
996 struct statfs statfs_buffer;
997 #elif defined(USE_STATVFS)
998 guint64 block_size;
999 struct statvfs statfs_buffer;
1000 #endif /* USE_STATFS */
1001 #endif /* G_OS_WIN32 */
1002 GFileAttributeMatcher *attribute_matcher;
1004 no_size = FALSE;
1006 #ifdef USE_STATFS
1008 #if STATFS_ARGS == 2
1009 statfs_result = statfs (local->filename, &statfs_buffer);
1010 #elif STATFS_ARGS == 4
1011 statfs_result = statfs (local->filename, &statfs_buffer,
1012 sizeof (statfs_buffer), 0);
1013 #endif /* STATFS_ARGS == 2 */
1014 block_size = statfs_buffer.f_bsize;
1016 /* Many backends can't report free size (for instance the gvfs fuse
1017 backend for backend not supporting this), and set f_bfree to 0,
1018 but it can be 0 for real too. We treat the available == 0 and
1019 free == 0 case as "both of these are invalid".
1021 #ifndef G_OS_WIN32
1022 if (statfs_result == 0 &&
1023 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
1024 no_size = TRUE;
1025 #endif /* G_OS_WIN32 */
1027 #elif defined(USE_STATVFS)
1028 statfs_result = statvfs (local->filename, &statfs_buffer);
1029 block_size = statfs_buffer.f_frsize;
1030 #endif /* USE_STATFS */
1032 if (statfs_result == -1)
1034 int errsv = errno;
1036 g_set_io_error (error,
1037 _("Error getting filesystem info for %s: %s"),
1038 file, errsv);
1039 return NULL;
1042 info = g_file_info_new ();
1044 attribute_matcher = g_file_attribute_matcher_new (attributes);
1046 if (!no_size &&
1047 g_file_attribute_matcher_matches (attribute_matcher,
1048 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1050 #ifdef G_OS_WIN32
1051 gchar *localdir = g_path_get_dirname (local->filename);
1052 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1053 ULARGE_INTEGER li;
1055 g_free (localdir);
1056 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1057 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1058 g_free (wdirname);
1059 #else
1060 #if defined(USE_STATFS) || defined(USE_STATVFS)
1061 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1062 #endif
1063 #endif
1065 if (!no_size &&
1066 g_file_attribute_matcher_matches (attribute_matcher,
1067 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1069 #ifdef G_OS_WIN32
1070 gchar *localdir = g_path_get_dirname (local->filename);
1071 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1072 ULARGE_INTEGER li;
1074 g_free (localdir);
1075 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1076 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1077 g_free (wdirname);
1078 #else
1079 #if defined(USE_STATFS) || defined(USE_STATVFS)
1080 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1081 #endif
1082 #endif /* G_OS_WIN32 */
1085 if (!no_size &&
1086 g_file_attribute_matcher_matches (attribute_matcher,
1087 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1089 #ifdef G_OS_WIN32
1090 gchar *localdir = g_path_get_dirname (local->filename);
1091 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1092 ULARGE_INTEGER li_free;
1093 ULARGE_INTEGER li_total;
1095 g_free (localdir);
1096 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1097 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1098 g_free (wdirname);
1099 #else
1100 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1101 #endif /* G_OS_WIN32 */
1104 #ifndef G_OS_WIN32
1105 #ifdef USE_STATFS
1106 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1107 fstype = g_strdup (statfs_buffer.f_fstypename);
1108 #else
1109 fstype = get_fs_type (statfs_buffer.f_type);
1110 #endif
1112 #elif defined(USE_STATVFS)
1113 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1114 fstype = g_strdup (statfs_buffer.f_fstypename);
1115 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1116 fstype = g_strdup (statfs_buffer.f_basetype);
1117 #else
1118 fstype = NULL;
1119 #endif
1120 #endif /* USE_STATFS */
1122 if (fstype &&
1123 g_file_attribute_matcher_matches (attribute_matcher,
1124 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1125 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1126 #endif /* G_OS_WIN32 */
1128 if (g_file_attribute_matcher_matches (attribute_matcher,
1129 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1131 #ifdef G_OS_WIN32
1132 get_filesystem_readonly (info, local->filename);
1133 #else
1134 get_mount_info (info, local->filename, attribute_matcher);
1135 #endif /* G_OS_WIN32 */
1138 if (g_file_attribute_matcher_matches (attribute_matcher,
1139 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
1140 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE,
1141 g_local_file_is_remote (local->filename));
1143 g_file_attribute_matcher_unref (attribute_matcher);
1145 return info;
1148 static GMount *
1149 g_local_file_find_enclosing_mount (GFile *file,
1150 GCancellable *cancellable,
1151 GError **error)
1153 GLocalFile *local = G_LOCAL_FILE (file);
1154 GStatBuf buf;
1155 char *mountpoint;
1156 GMount *mount;
1158 if (g_lstat (local->filename, &buf) != 0)
1159 goto error;
1161 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1162 if (mountpoint == NULL)
1163 goto error;
1165 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1166 g_free (mountpoint);
1167 if (mount)
1168 return mount;
1170 error:
1171 g_set_io_error (error,
1172 /* Translators: This is an error message when trying to find
1173 * the enclosing (user visible) mount of a file, but none
1174 * exists.
1176 _("Containing mount for file %s not found"),
1177 file, 0);
1179 return NULL;
1182 static GFile *
1183 g_local_file_set_display_name (GFile *file,
1184 const char *display_name,
1185 GCancellable *cancellable,
1186 GError **error)
1188 GLocalFile *local, *new_local;
1189 GFile *new_file, *parent;
1190 GStatBuf statbuf;
1191 GVfsClass *class;
1192 GVfs *vfs;
1193 int errsv;
1195 parent = g_file_get_parent (file);
1196 if (parent == NULL)
1198 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1199 _("Can’t rename root directory"));
1200 return NULL;
1203 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1204 g_object_unref (parent);
1206 if (new_file == NULL)
1207 return NULL;
1208 local = G_LOCAL_FILE (file);
1209 new_local = G_LOCAL_FILE (new_file);
1211 if (g_lstat (new_local->filename, &statbuf) == -1)
1213 errsv = errno;
1215 if (errsv != ENOENT)
1217 g_set_io_error (error, _("Error renaming file %s: %s"), new_file, errsv);
1218 return NULL;
1221 else
1223 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
1224 _("Can’t rename file, filename already exists"));
1225 return NULL;
1228 if (g_rename (local->filename, new_local->filename) == -1)
1230 errsv = errno;
1232 if (errsv == EINVAL)
1233 /* We can't get a rename file into itself error here,
1234 * so this must be an invalid filename, on e.g. FAT
1236 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME,
1237 _("Invalid filename"));
1238 else
1239 g_set_io_error (error,
1240 _("Error renaming file %s: %s"),
1241 file, errsv);
1242 g_object_unref (new_file);
1243 return NULL;
1246 vfs = g_vfs_get_default ();
1247 class = G_VFS_GET_CLASS (vfs);
1248 if (class->local_file_moved)
1249 class->local_file_moved (vfs, local->filename, new_local->filename);
1251 return new_file;
1254 static GFileInfo *
1255 g_local_file_query_info (GFile *file,
1256 const char *attributes,
1257 GFileQueryInfoFlags flags,
1258 GCancellable *cancellable,
1259 GError **error)
1261 GLocalFile *local = G_LOCAL_FILE (file);
1262 GFileInfo *info;
1263 GFileAttributeMatcher *matcher;
1264 char *basename, *dirname;
1265 GLocalParentFileInfo parent_info;
1267 matcher = g_file_attribute_matcher_new (attributes);
1269 basename = g_path_get_basename (local->filename);
1271 dirname = g_path_get_dirname (local->filename);
1272 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1273 g_free (dirname);
1275 info = _g_local_file_info_get (basename, local->filename,
1276 matcher, flags, &parent_info,
1277 error);
1280 _g_local_file_info_free_parent_info (&parent_info);
1281 g_free (basename);
1283 g_file_attribute_matcher_unref (matcher);
1285 return info;
1288 static GFileAttributeInfoList *
1289 g_local_file_query_settable_attributes (GFile *file,
1290 GCancellable *cancellable,
1291 GError **error)
1293 return g_file_attribute_info_list_ref (local_writable_attributes);
1296 static GFileAttributeInfoList *
1297 g_local_file_query_writable_namespaces (GFile *file,
1298 GCancellable *cancellable,
1299 GError **error)
1301 GFileAttributeInfoList *list;
1302 GVfsClass *class;
1303 GVfs *vfs;
1305 if (g_once_init_enter (&local_writable_namespaces))
1307 /* Writable namespaces: */
1309 list = g_file_attribute_info_list_new ();
1311 #ifdef HAVE_XATTR
1312 g_file_attribute_info_list_add (list,
1313 "xattr",
1314 G_FILE_ATTRIBUTE_TYPE_STRING,
1315 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1316 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1317 g_file_attribute_info_list_add (list,
1318 "xattr-sys",
1319 G_FILE_ATTRIBUTE_TYPE_STRING,
1320 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1321 #endif
1323 vfs = g_vfs_get_default ();
1324 class = G_VFS_GET_CLASS (vfs);
1325 if (class->add_writable_namespaces)
1326 class->add_writable_namespaces (vfs, list);
1328 g_once_init_leave (&local_writable_namespaces, (gsize)list);
1330 list = (GFileAttributeInfoList *)local_writable_namespaces;
1332 return g_file_attribute_info_list_ref (list);
1335 static gboolean
1336 g_local_file_set_attribute (GFile *file,
1337 const char *attribute,
1338 GFileAttributeType type,
1339 gpointer value_p,
1340 GFileQueryInfoFlags flags,
1341 GCancellable *cancellable,
1342 GError **error)
1344 GLocalFile *local = G_LOCAL_FILE (file);
1346 return _g_local_file_info_set_attribute (local->filename,
1347 attribute,
1348 type,
1349 value_p,
1350 flags,
1351 cancellable,
1352 error);
1355 static gboolean
1356 g_local_file_set_attributes_from_info (GFile *file,
1357 GFileInfo *info,
1358 GFileQueryInfoFlags flags,
1359 GCancellable *cancellable,
1360 GError **error)
1362 GLocalFile *local = G_LOCAL_FILE (file);
1363 int res, chained_res;
1364 GFileIface *default_iface;
1366 res = _g_local_file_info_set_attributes (local->filename,
1367 info, flags,
1368 cancellable,
1369 error);
1371 if (!res)
1372 error = NULL; /* Don't write over error if further errors */
1374 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1376 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1378 return res && chained_res;
1381 static GFileInputStream *
1382 g_local_file_read (GFile *file,
1383 GCancellable *cancellable,
1384 GError **error)
1386 GLocalFile *local = G_LOCAL_FILE (file);
1387 int fd, ret;
1388 GLocalFileStat buf;
1390 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1391 if (fd == -1)
1393 int errsv = errno;
1395 #ifdef G_OS_WIN32
1396 if (errsv == EACCES)
1398 ret = _stati64 (local->filename, &buf);
1399 if (ret == 0 && S_ISDIR (buf.st_mode))
1400 errsv = EISDIR;
1402 #endif
1403 g_set_io_error (error,
1404 _("Error opening file %s: %s"),
1405 file, errsv);
1406 return NULL;
1409 #ifdef G_OS_WIN32
1410 ret = _fstati64 (fd, &buf);
1411 #else
1412 ret = fstat (fd, &buf);
1413 #endif
1415 if (ret == 0 && S_ISDIR (buf.st_mode))
1417 (void) g_close (fd, NULL);
1418 g_set_io_error (error,
1419 _("Error opening file %s: %s"),
1420 file, EISDIR);
1421 return NULL;
1424 return _g_local_file_input_stream_new (fd);
1427 static GFileOutputStream *
1428 g_local_file_append_to (GFile *file,
1429 GFileCreateFlags flags,
1430 GCancellable *cancellable,
1431 GError **error)
1433 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1434 flags, cancellable, error);
1437 static GFileOutputStream *
1438 g_local_file_create (GFile *file,
1439 GFileCreateFlags flags,
1440 GCancellable *cancellable,
1441 GError **error)
1443 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1444 FALSE, flags, NULL,
1445 cancellable, error);
1448 static GFileOutputStream *
1449 g_local_file_replace (GFile *file,
1450 const char *etag,
1451 gboolean make_backup,
1452 GFileCreateFlags flags,
1453 GCancellable *cancellable,
1454 GError **error)
1456 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1457 FALSE,
1458 etag, make_backup, flags, NULL,
1459 cancellable, error);
1462 static GFileIOStream *
1463 g_local_file_open_readwrite (GFile *file,
1464 GCancellable *cancellable,
1465 GError **error)
1467 GFileOutputStream *output;
1468 GFileIOStream *res;
1470 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1471 TRUE,
1472 cancellable, error);
1473 if (output == NULL)
1474 return NULL;
1476 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1477 g_object_unref (output);
1478 return res;
1481 static GFileIOStream *
1482 g_local_file_create_readwrite (GFile *file,
1483 GFileCreateFlags flags,
1484 GCancellable *cancellable,
1485 GError **error)
1487 GFileOutputStream *output;
1488 GFileIOStream *res;
1490 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1491 TRUE, flags, NULL,
1492 cancellable, error);
1493 if (output == NULL)
1494 return NULL;
1496 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1497 g_object_unref (output);
1498 return res;
1501 static GFileIOStream *
1502 g_local_file_replace_readwrite (GFile *file,
1503 const char *etag,
1504 gboolean make_backup,
1505 GFileCreateFlags flags,
1506 GCancellable *cancellable,
1507 GError **error)
1509 GFileOutputStream *output;
1510 GFileIOStream *res;
1512 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1513 TRUE,
1514 etag, make_backup, flags, NULL,
1515 cancellable, error);
1516 if (output == NULL)
1517 return NULL;
1519 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1520 g_object_unref (output);
1521 return res;
1524 static gboolean
1525 g_local_file_delete (GFile *file,
1526 GCancellable *cancellable,
1527 GError **error)
1529 GLocalFile *local = G_LOCAL_FILE (file);
1530 GVfsClass *class;
1531 GVfs *vfs;
1533 if (g_remove (local->filename) == -1)
1535 int errsv = errno;
1537 /* Posix allows EEXIST too, but the more sane error
1538 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1539 expects */
1540 if (errsv == EEXIST)
1541 errsv = ENOTEMPTY;
1543 g_set_io_error (error,
1544 _("Error removing file %s: %s"),
1545 file, errsv);
1546 return FALSE;
1549 vfs = g_vfs_get_default ();
1550 class = G_VFS_GET_CLASS (vfs);
1551 if (class->local_file_removed)
1552 class->local_file_removed (vfs, local->filename);
1554 return TRUE;
1557 #ifndef G_OS_WIN32
1559 static char *
1560 strip_trailing_slashes (const char *path)
1562 char *path_copy;
1563 int len;
1565 path_copy = g_strdup (path);
1566 len = strlen (path_copy);
1567 while (len > 1 && path_copy[len-1] == '/')
1568 path_copy[--len] = 0;
1570 return path_copy;
1573 static char *
1574 expand_symlink (const char *link)
1576 char *resolved, *canonical, *parent, *link2;
1577 char symlink_value[4096];
1578 #ifdef G_OS_WIN32
1579 #else
1580 ssize_t res;
1581 #endif
1583 #ifdef G_OS_WIN32
1584 #else
1585 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1587 if (res == -1)
1588 return g_strdup (link);
1589 symlink_value[res] = 0;
1590 #endif
1592 if (g_path_is_absolute (symlink_value))
1593 return canonicalize_filename (symlink_value);
1594 else
1596 link2 = strip_trailing_slashes (link);
1597 parent = g_path_get_dirname (link2);
1598 g_free (link2);
1600 resolved = g_build_filename (parent, symlink_value, NULL);
1601 g_free (parent);
1603 canonical = canonicalize_filename (resolved);
1605 g_free (resolved);
1607 return canonical;
1611 static char *
1612 get_parent (const char *path,
1613 dev_t *parent_dev)
1615 char *parent, *tmp;
1616 GStatBuf parent_stat;
1617 int num_recursions;
1618 char *path_copy;
1620 path_copy = strip_trailing_slashes (path);
1622 parent = g_path_get_dirname (path_copy);
1623 if (strcmp (parent, ".") == 0 ||
1624 strcmp (parent, path_copy) == 0)
1626 g_free (parent);
1627 g_free (path_copy);
1628 return NULL;
1630 g_free (path_copy);
1632 num_recursions = 0;
1633 do {
1634 if (g_lstat (parent, &parent_stat) != 0)
1636 g_free (parent);
1637 return NULL;
1640 if (S_ISLNK (parent_stat.st_mode))
1642 tmp = parent;
1643 parent = expand_symlink (parent);
1644 g_free (tmp);
1647 num_recursions++;
1648 if (num_recursions > 12)
1650 g_free (parent);
1651 return NULL;
1653 } while (S_ISLNK (parent_stat.st_mode));
1655 *parent_dev = parent_stat.st_dev;
1657 return parent;
1660 static char *
1661 expand_all_symlinks (const char *path)
1663 char *parent, *parent_expanded;
1664 char *basename, *res;
1665 dev_t parent_dev;
1667 parent = get_parent (path, &parent_dev);
1668 if (parent)
1670 parent_expanded = expand_all_symlinks (parent);
1671 g_free (parent);
1672 basename = g_path_get_basename (path);
1673 res = g_build_filename (parent_expanded, basename, NULL);
1674 g_free (basename);
1675 g_free (parent_expanded);
1677 else
1678 res = g_strdup (path);
1680 return res;
1683 static char *
1684 find_mountpoint_for (const char *file,
1685 dev_t dev)
1687 char *dir, *parent;
1688 dev_t dir_dev, parent_dev;
1690 dir = g_strdup (file);
1691 dir_dev = dev;
1693 while (1)
1695 parent = get_parent (dir, &parent_dev);
1696 if (parent == NULL)
1697 return dir;
1699 if (parent_dev != dir_dev)
1701 g_free (parent);
1702 return dir;
1705 g_free (dir);
1706 dir = parent;
1710 char *
1711 _g_local_file_find_topdir_for (const char *file)
1713 char *dir;
1714 char *mountpoint = NULL;
1715 dev_t dir_dev;
1717 dir = get_parent (file, &dir_dev);
1718 if (dir == NULL)
1719 return NULL;
1721 mountpoint = find_mountpoint_for (dir, dir_dev);
1722 g_free (dir);
1724 return mountpoint;
1727 static char *
1728 get_unique_filename (const char *basename,
1729 int id)
1731 const char *dot;
1733 if (id == 1)
1734 return g_strdup (basename);
1736 dot = strchr (basename, '.');
1737 if (dot)
1738 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1739 else
1740 return g_strdup_printf ("%s.%d", basename, id);
1743 static gboolean
1744 path_has_prefix (const char *path,
1745 const char *prefix)
1747 int prefix_len;
1749 if (prefix == NULL)
1750 return TRUE;
1752 prefix_len = strlen (prefix);
1754 if (strncmp (path, prefix, prefix_len) == 0 &&
1755 (prefix_len == 0 || /* empty prefix always matches */
1756 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1757 path[prefix_len] == 0 ||
1758 path[prefix_len] == '/'))
1759 return TRUE;
1761 return FALSE;
1764 static char *
1765 try_make_relative (const char *path,
1766 const char *base)
1768 char *path2, *base2;
1769 char *relative;
1771 path2 = expand_all_symlinks (path);
1772 base2 = expand_all_symlinks (base);
1774 relative = NULL;
1775 if (path_has_prefix (path2, base2))
1777 relative = path2 + strlen (base2);
1778 while (*relative == '/')
1779 relative ++;
1780 relative = g_strdup (relative);
1782 g_free (path2);
1783 g_free (base2);
1785 if (relative)
1786 return relative;
1788 /* Failed, use abs path */
1789 return g_strdup (path);
1792 gboolean
1793 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1795 static gsize home_dev_set = 0;
1796 static dev_t home_dev;
1797 char *topdir, *globaldir, *trashdir, *tmpname;
1798 uid_t uid;
1799 char uid_str[32];
1800 GStatBuf global_stat, trash_stat;
1801 gboolean res;
1803 if (g_once_init_enter (&home_dev_set))
1805 GStatBuf home_stat;
1807 g_stat (g_get_home_dir (), &home_stat);
1808 home_dev = home_stat.st_dev;
1809 g_once_init_leave (&home_dev_set, 1);
1812 /* Assume we can trash to the home */
1813 if (dir_dev == home_dev)
1814 return TRUE;
1816 topdir = find_mountpoint_for (dirname, dir_dev);
1817 if (topdir == NULL)
1818 return FALSE;
1820 globaldir = g_build_filename (topdir, ".Trash", NULL);
1821 if (g_lstat (globaldir, &global_stat) == 0 &&
1822 S_ISDIR (global_stat.st_mode) &&
1823 (global_stat.st_mode & S_ISVTX) != 0)
1825 /* got a toplevel sysadmin created dir, assume we
1826 * can trash to it (we should be able to create a dir)
1827 * This fails for the FAT case where the ownership of
1828 * that dir would be wrong though..
1830 g_free (globaldir);
1831 g_free (topdir);
1832 return TRUE;
1834 g_free (globaldir);
1836 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1837 uid = geteuid ();
1838 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1840 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1841 trashdir = g_build_filename (topdir, tmpname, NULL);
1842 g_free (tmpname);
1844 if (g_lstat (trashdir, &trash_stat) == 0)
1846 g_free (topdir);
1847 g_free (trashdir);
1848 return S_ISDIR (trash_stat.st_mode) &&
1849 trash_stat.st_uid == uid;
1851 g_free (trashdir);
1853 /* User specific trash didn't exist, can we create it? */
1854 res = g_access (topdir, W_OK) == 0;
1855 g_free (topdir);
1857 return res;
1860 #ifdef G_OS_UNIX
1861 gboolean
1862 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1864 gboolean ret = FALSE;
1865 gchar *mount_dir = NULL;
1866 size_t mount_dir_len;
1867 GStatBuf statbuf;
1869 if (!g_str_has_suffix (path, "/lost+found"))
1870 goto out;
1872 mount_dir = find_mountpoint_for (path, path_dev);
1873 if (mount_dir == NULL)
1874 goto out;
1876 mount_dir_len = strlen (mount_dir);
1877 /* We special-case rootfs ('/') since it's the only case where
1878 * mount_dir ends in '/'
1880 if (mount_dir_len == 1)
1881 mount_dir_len--;
1882 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1883 goto out;
1885 if (g_lstat (path, &statbuf) != 0)
1886 goto out;
1888 if (!(S_ISDIR (statbuf.st_mode) &&
1889 statbuf.st_uid == 0 &&
1890 statbuf.st_gid == 0))
1891 goto out;
1893 ret = TRUE;
1895 out:
1896 g_free (mount_dir);
1897 return ret;
1899 #endif
1901 static gboolean
1902 g_local_file_trash (GFile *file,
1903 GCancellable *cancellable,
1904 GError **error)
1906 GLocalFile *local = G_LOCAL_FILE (file);
1907 GStatBuf file_stat, home_stat;
1908 const char *homedir;
1909 char *trashdir, *topdir, *infodir, *filesdir;
1910 char *basename, *trashname, *trashfile, *infoname, *infofile;
1911 char *original_name, *original_name_escaped;
1912 int i;
1913 char *data;
1914 gboolean is_homedir_trash;
1915 char delete_time[32];
1916 int fd;
1917 GStatBuf trash_stat, global_stat;
1918 char *dirname, *globaldir;
1919 GVfsClass *class;
1920 GVfs *vfs;
1921 int errsv;
1923 if (g_lstat (local->filename, &file_stat) != 0)
1925 errsv = errno;
1927 g_set_io_error (error,
1928 _("Error trashing file %s: %s"),
1929 file, errsv);
1930 return FALSE;
1933 homedir = g_get_home_dir ();
1934 g_stat (homedir, &home_stat);
1936 is_homedir_trash = FALSE;
1937 trashdir = NULL;
1938 if (file_stat.st_dev == home_stat.st_dev)
1940 is_homedir_trash = TRUE;
1941 errno = 0;
1942 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1943 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1945 char *display_name;
1946 errsv = errno;
1948 display_name = g_filename_display_name (trashdir);
1949 g_set_error (error, G_IO_ERROR,
1950 g_io_error_from_errno (errsv),
1951 _("Unable to create trash dir %s: %s"),
1952 display_name, g_strerror (errsv));
1953 g_free (display_name);
1954 g_free (trashdir);
1955 return FALSE;
1957 topdir = g_strdup (g_get_user_data_dir ());
1959 else
1961 uid_t uid;
1962 char uid_str[32];
1964 uid = geteuid ();
1965 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1967 topdir = _g_local_file_find_topdir_for (local->filename);
1968 if (topdir == NULL)
1970 g_set_io_error (error,
1971 _("Unable to find toplevel directory to trash %s"),
1972 file, G_IO_ERROR_NOT_SUPPORTED);
1973 return FALSE;
1976 /* Try looking for global trash dir $topdir/.Trash/$uid */
1977 globaldir = g_build_filename (topdir, ".Trash", NULL);
1978 if (g_lstat (globaldir, &global_stat) == 0 &&
1979 S_ISDIR (global_stat.st_mode) &&
1980 (global_stat.st_mode & S_ISVTX) != 0)
1982 trashdir = g_build_filename (globaldir, uid_str, NULL);
1984 if (g_lstat (trashdir, &trash_stat) == 0)
1986 if (!S_ISDIR (trash_stat.st_mode) ||
1987 trash_stat.st_uid != uid)
1989 /* Not a directory or not owned by user, ignore */
1990 g_free (trashdir);
1991 trashdir = NULL;
1994 else if (g_mkdir (trashdir, 0700) == -1)
1996 g_free (trashdir);
1997 trashdir = NULL;
2000 g_free (globaldir);
2002 if (trashdir == NULL)
2004 gboolean tried_create;
2006 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2007 dirname = g_strdup_printf (".Trash-%s", uid_str);
2008 trashdir = g_build_filename (topdir, dirname, NULL);
2009 g_free (dirname);
2011 tried_create = FALSE;
2013 retry:
2014 if (g_lstat (trashdir, &trash_stat) == 0)
2016 if (!S_ISDIR (trash_stat.st_mode) ||
2017 trash_stat.st_uid != uid)
2019 /* Remove the failed directory */
2020 if (tried_create)
2021 g_remove (trashdir);
2023 /* Not a directory or not owned by user, ignore */
2024 g_free (trashdir);
2025 trashdir = NULL;
2028 else
2030 if (!tried_create &&
2031 g_mkdir (trashdir, 0700) != -1)
2033 /* Ensure that the created dir has the right uid etc.
2034 This might fail on e.g. a FAT dir */
2035 tried_create = TRUE;
2036 goto retry;
2038 else
2040 g_free (trashdir);
2041 trashdir = NULL;
2046 if (trashdir == NULL)
2048 g_free (topdir);
2049 g_set_io_error (error,
2050 _("Unable to find or create trash directory for %s"),
2051 file, G_IO_ERROR_NOT_SUPPORTED);
2052 return FALSE;
2056 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2058 infodir = g_build_filename (trashdir, "info", NULL);
2059 filesdir = g_build_filename (trashdir, "files", NULL);
2060 g_free (trashdir);
2062 /* Make sure we have the subdirectories */
2063 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2064 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2066 g_free (topdir);
2067 g_free (infodir);
2068 g_free (filesdir);
2069 g_set_io_error (error,
2070 _("Unable to find or create trash directory for %s"),
2071 file, G_IO_ERROR_NOT_SUPPORTED);
2072 return FALSE;
2075 basename = g_path_get_basename (local->filename);
2076 i = 1;
2077 trashname = NULL;
2078 infofile = NULL;
2079 do {
2080 g_free (trashname);
2081 g_free (infofile);
2083 trashname = get_unique_filename (basename, i++);
2084 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2085 infofile = g_build_filename (infodir, infoname, NULL);
2086 g_free (infoname);
2088 fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
2089 errsv = errno;
2090 } while (fd == -1 && errsv == EEXIST);
2092 g_free (basename);
2093 g_free (infodir);
2095 if (fd == -1)
2097 errsv = errno;
2099 g_free (filesdir);
2100 g_free (topdir);
2101 g_free (trashname);
2102 g_free (infofile);
2104 g_set_io_error (error,
2105 _("Unable to create trashing info file for %s: %s"),
2106 file, errsv);
2107 return FALSE;
2110 (void) g_close (fd, NULL);
2112 /* Write the full content of the info file before trashing to make
2113 * sure someone doesn't read an empty file. See #749314
2116 /* Use absolute names for homedir */
2117 if (is_homedir_trash)
2118 original_name = g_strdup (local->filename);
2119 else
2120 original_name = try_make_relative (local->filename, topdir);
2121 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2123 g_free (original_name);
2124 g_free (topdir);
2127 time_t t;
2128 struct tm now;
2129 t = time (NULL);
2130 localtime_r (&t, &now);
2131 delete_time[0] = 0;
2132 strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
2135 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2136 original_name_escaped, delete_time);
2138 g_file_set_contents (infofile, data, -1, NULL);
2140 /* TODO: Maybe we should verify that you can delete the file from the trash
2141 * before moving it? OTOH, that is hard, as it needs a recursive scan
2144 trashfile = g_build_filename (filesdir, trashname, NULL);
2146 g_free (filesdir);
2148 if (g_rename (local->filename, trashfile) == -1)
2150 errsv = errno;
2152 g_unlink (infofile);
2154 g_free (trashname);
2155 g_free (infofile);
2156 g_free (trashfile);
2158 if (errsv == EXDEV)
2159 /* The trash dir was actually on another fs anyway!?
2160 * This can happen when the same device is mounted multiple
2161 * times, or with bind mounts of the same fs.
2163 g_set_io_error (error,
2164 _("Unable to trash file %s across filesystem boundaries"),
2165 file, ENOTSUP);
2166 else
2167 g_set_io_error (error,
2168 _("Unable to trash file %s: %s"),
2169 file, errsv);
2170 return FALSE;
2173 vfs = g_vfs_get_default ();
2174 class = G_VFS_GET_CLASS (vfs);
2175 if (class->local_file_moved)
2176 class->local_file_moved (vfs, local->filename, trashfile);
2178 g_free (trashfile);
2180 /* TODO: Do we need to update mtime/atime here after the move? */
2182 g_free (infofile);
2183 g_free (data);
2185 g_free (original_name_escaped);
2186 g_free (trashname);
2188 return TRUE;
2190 #else /* G_OS_WIN32 */
2191 gboolean
2192 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2194 return FALSE; /* XXX ??? */
2197 static gboolean
2198 g_local_file_trash (GFile *file,
2199 GCancellable *cancellable,
2200 GError **error)
2202 GLocalFile *local = G_LOCAL_FILE (file);
2203 SHFILEOPSTRUCTW op = {0};
2204 gboolean success;
2205 wchar_t *wfilename;
2206 long len;
2208 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2209 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2210 wfilename = g_renew (wchar_t, wfilename, len + 2);
2211 wfilename[len + 1] = 0;
2213 op.wFunc = FO_DELETE;
2214 op.pFrom = wfilename;
2215 op.fFlags = FOF_ALLOWUNDO;
2217 success = SHFileOperationW (&op) == 0;
2219 if (success && op.fAnyOperationsAborted)
2221 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2222 g_cancellable_cancel (cancellable);
2223 g_set_io_error (error,
2224 _("Unable to trash file %s: %s"),
2225 file, ECANCELED);
2226 success = FALSE;
2228 else if (!success)
2229 g_set_io_error (error,
2230 _("Unable to trash file %s"),
2231 file, 0);
2233 g_free (wfilename);
2234 return success;
2236 #endif /* G_OS_WIN32 */
2238 static gboolean
2239 g_local_file_make_directory (GFile *file,
2240 GCancellable *cancellable,
2241 GError **error)
2243 GLocalFile *local = G_LOCAL_FILE (file);
2245 if (g_mkdir (local->filename, 0777) == -1)
2247 int errsv = errno;
2249 if (errsv == EINVAL)
2250 /* This must be an invalid filename, on e.g. FAT */
2251 g_set_error_literal (error, G_IO_ERROR,
2252 G_IO_ERROR_INVALID_FILENAME,
2253 _("Invalid filename"));
2254 else
2255 g_set_io_error (error,
2256 _("Error creating directory %s: %s"),
2257 file, errsv);
2258 return FALSE;
2261 return TRUE;
2264 static gboolean
2265 g_local_file_make_symbolic_link (GFile *file,
2266 const char *symlink_value,
2267 GCancellable *cancellable,
2268 GError **error)
2270 #ifdef HAVE_SYMLINK
2271 GLocalFile *local = G_LOCAL_FILE (file);
2273 if (symlink (symlink_value, local->filename) == -1)
2275 int errsv = errno;
2277 if (errsv == EINVAL)
2278 /* This must be an invalid filename, on e.g. FAT */
2279 g_set_error_literal (error, G_IO_ERROR,
2280 G_IO_ERROR_INVALID_FILENAME,
2281 _("Invalid filename"));
2282 else if (errsv == EPERM)
2283 g_set_error (error, G_IO_ERROR,
2284 G_IO_ERROR_NOT_SUPPORTED,
2285 _("Filesystem does not support symbolic links"));
2286 else
2287 g_set_io_error (error,
2288 _("Error making symbolic link %s: %s"),
2289 file, errsv);
2290 return FALSE;
2292 return TRUE;
2293 #else
2294 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Symbolic links not supported"));
2295 return FALSE;
2296 #endif
2300 static gboolean
2301 g_local_file_copy (GFile *source,
2302 GFile *destination,
2303 GFileCopyFlags flags,
2304 GCancellable *cancellable,
2305 GFileProgressCallback progress_callback,
2306 gpointer progress_callback_data,
2307 GError **error)
2309 /* Fall back to default copy */
2310 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2311 return FALSE;
2314 static gboolean
2315 g_local_file_move (GFile *source,
2316 GFile *destination,
2317 GFileCopyFlags flags,
2318 GCancellable *cancellable,
2319 GFileProgressCallback progress_callback,
2320 gpointer progress_callback_data,
2321 GError **error)
2323 GLocalFile *local_source, *local_destination;
2324 GStatBuf statbuf;
2325 gboolean destination_exist, source_is_dir;
2326 char *backup_name;
2327 int res;
2328 off_t source_size;
2329 GVfsClass *class;
2330 GVfs *vfs;
2332 if (!G_IS_LOCAL_FILE (source) ||
2333 !G_IS_LOCAL_FILE (destination))
2335 /* Fall back to default move */
2336 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2337 return FALSE;
2340 local_source = G_LOCAL_FILE (source);
2341 local_destination = G_LOCAL_FILE (destination);
2343 res = g_lstat (local_source->filename, &statbuf);
2344 if (res == -1)
2346 int errsv = errno;
2348 g_set_io_error (error,
2349 _("Error moving file %s: %s"),
2350 source, errsv);
2351 return FALSE;
2354 source_is_dir = S_ISDIR (statbuf.st_mode);
2355 source_size = statbuf.st_size;
2357 destination_exist = FALSE;
2358 res = g_lstat (local_destination->filename, &statbuf);
2359 if (res == 0)
2361 destination_exist = TRUE; /* Target file exists */
2363 if (flags & G_FILE_COPY_OVERWRITE)
2365 /* Always fail on dirs, even with overwrite */
2366 if (S_ISDIR (statbuf.st_mode))
2368 if (source_is_dir)
2369 g_set_error_literal (error,
2370 G_IO_ERROR,
2371 G_IO_ERROR_WOULD_MERGE,
2372 _("Can’t move directory over directory"));
2373 else
2374 g_set_error_literal (error,
2375 G_IO_ERROR,
2376 G_IO_ERROR_IS_DIRECTORY,
2377 _("Can’t copy over directory"));
2378 return FALSE;
2381 else
2383 g_set_io_error (error,
2384 _("Error moving file %s: %s"),
2385 source, EEXIST);
2386 return FALSE;
2390 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2392 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2393 if (g_rename (local_destination->filename, backup_name) == -1)
2395 g_set_error_literal (error,
2396 G_IO_ERROR,
2397 G_IO_ERROR_CANT_CREATE_BACKUP,
2398 _("Backup file creation failed"));
2399 g_free (backup_name);
2400 return FALSE;
2402 g_free (backup_name);
2403 destination_exist = FALSE; /* It did, but no more */
2406 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2408 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2409 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2410 res = g_unlink (local_destination->filename);
2411 if (res == -1)
2413 int errsv = errno;
2415 g_set_error (error, G_IO_ERROR,
2416 g_io_error_from_errno (errsv),
2417 _("Error removing target file: %s"),
2418 g_strerror (errsv));
2419 return FALSE;
2423 if (g_rename (local_source->filename, local_destination->filename) == -1)
2425 int errsv = errno;
2427 if (errsv == EXDEV)
2428 /* This will cause the fallback code to run */
2429 g_set_error_literal (error, G_IO_ERROR,
2430 G_IO_ERROR_NOT_SUPPORTED,
2431 _("Move between mounts not supported"));
2432 else if (errsv == EINVAL)
2433 /* This must be an invalid filename, on e.g. FAT, or
2434 we're trying to move the file into itself...
2435 We return invalid filename for both... */
2436 g_set_error_literal (error, G_IO_ERROR,
2437 G_IO_ERROR_INVALID_FILENAME,
2438 _("Invalid filename"));
2439 else
2440 g_set_io_error (error,
2441 _("Error moving file %s: %s"),
2442 source, errsv);
2443 return FALSE;
2446 vfs = g_vfs_get_default ();
2447 class = G_VFS_GET_CLASS (vfs);
2448 if (class->local_file_moved)
2449 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2451 /* Make sure we send full copied size */
2452 if (progress_callback)
2453 progress_callback (source_size, source_size, progress_callback_data);
2455 return TRUE;
2458 #ifdef G_OS_WIN32
2460 gboolean
2461 g_local_file_is_remote (const gchar *filename)
2463 return FALSE;
2466 #else
2468 static gboolean
2469 is_remote_fs (const gchar *filename)
2471 const char *fsname = NULL;
2473 #ifdef USE_STATFS
2474 struct statfs statfs_buffer;
2475 int statfs_result = 0;
2477 #if STATFS_ARGS == 2
2478 statfs_result = statfs (filename, &statfs_buffer);
2479 #elif STATFS_ARGS == 4
2480 statfs_result = statfs (filename, &statfs_buffer, sizeof (statfs_buffer), 0);
2481 #endif
2483 #elif defined(USE_STATVFS)
2484 struct statvfs statfs_buffer;
2485 int statfs_result = 0;
2487 statfs_result = statvfs (filename, &statfs_buffer);
2488 #else
2489 return FALSE;
2490 #endif
2492 if (statfs_result == -1)
2493 return FALSE;
2495 #ifdef USE_STATFS
2496 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
2497 fsname = statfs_buffer.f_fstypename;
2498 #else
2499 fsname = get_fs_type (statfs_buffer.f_type);
2500 #endif
2502 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
2503 fsname = statfs_buffer.f_basetype;
2504 #endif
2506 if (fsname != NULL)
2508 if (strcmp (fsname, "nfs") == 0)
2509 return TRUE;
2510 if (strcmp (fsname, "nfs4") == 0)
2511 return TRUE;
2514 return FALSE;
2517 gboolean
2518 g_local_file_is_remote (const gchar *filename)
2520 static gboolean remote_home;
2521 static gsize initialized;
2522 const gchar *home;
2524 home = g_get_home_dir ();
2525 if (path_has_prefix (filename, home))
2527 if (g_once_init_enter (&initialized))
2529 remote_home = is_remote_fs (home);
2530 g_once_init_leave (&initialized, TRUE);
2532 return remote_home;
2535 return FALSE;
2537 #endif /* !G_OS_WIN32 */
2539 static GFileMonitor*
2540 g_local_file_monitor_dir (GFile *file,
2541 GFileMonitorFlags flags,
2542 GCancellable *cancellable,
2543 GError **error)
2545 GLocalFile *local_file = G_LOCAL_FILE (file);
2547 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2550 static GFileMonitor*
2551 g_local_file_monitor_file (GFile *file,
2552 GFileMonitorFlags flags,
2553 GCancellable *cancellable,
2554 GError **error)
2556 GLocalFile *local_file = G_LOCAL_FILE (file);
2558 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2561 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2563 * If available, we use fopenat() in preference to filenames for
2564 * efficiency and safety reasons. We know that fopenat() is available
2565 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2566 * defined as a macro.
2568 * We use a linked list of stack-allocated GSList nodes in order to be
2569 * able to reconstruct the filename for error messages. We actually
2570 * pass the filename to operate on through the top node of the list.
2572 * In case we're using openat(), this top filename will be a basename
2573 * which should be opened in the directory which has also had its fd
2574 * passed along. If we're not using openat() then it will be a full
2575 * absolute filename.
2578 static gboolean
2579 g_local_file_measure_size_error (GFileMeasureFlags flags,
2580 gint saved_errno,
2581 GSList *name,
2582 GError **error)
2584 /* Only report an error if we were at the toplevel or if the caller
2585 * requested reporting of all errors.
2587 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2589 GString *filename;
2590 GSList *node;
2592 /* Skip some work if there is no error return */
2593 if (!error)
2594 return FALSE;
2596 #ifdef AT_FDCWD
2597 /* If using openat() we need to rebuild the filename for the message */
2598 filename = g_string_new (name->data);
2599 for (node = name->next; node; node = node->next)
2601 gchar *utf8;
2603 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2604 utf8 = g_filename_display_name (node->data);
2605 g_string_prepend (filename, utf8);
2606 g_free (utf8);
2608 #else
2610 gchar *utf8;
2612 /* Otherwise, we already have it, so just use it. */
2613 node = name;
2614 filename = g_string_new (NULL);
2615 utf8 = g_filename_display_name (node->data);
2616 g_string_append (filename, utf8);
2617 g_free (utf8);
2619 #endif
2621 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2622 _("Could not determine the disk usage of %s: %s"),
2623 filename->str, g_strerror (saved_errno));
2625 g_string_free (filename, TRUE);
2627 return FALSE;
2630 else
2631 /* We're not reporting this error... */
2632 return TRUE;
2635 typedef struct
2637 GFileMeasureFlags flags;
2638 dev_t contained_on;
2639 GCancellable *cancellable;
2641 GFileMeasureProgressCallback progress_callback;
2642 gpointer progress_data;
2644 guint64 disk_usage;
2645 guint64 num_dirs;
2646 guint64 num_files;
2648 guint64 last_progress_report;
2649 } MeasureState;
2651 static gboolean
2652 g_local_file_measure_size_of_contents (gint fd,
2653 GSList *dir_name,
2654 MeasureState *state,
2655 GError **error);
2657 static gboolean
2658 g_local_file_measure_size_of_file (gint parent_fd,
2659 GSList *name,
2660 MeasureState *state,
2661 GError **error)
2663 GLocalFileStat buf;
2665 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2666 return FALSE;
2668 #if defined (AT_FDCWD)
2669 if (fstatat (parent_fd, name->data, &buf, AT_SYMLINK_NOFOLLOW) != 0)
2671 int errsv = errno;
2672 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2674 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2675 if (g_lstat (name->data, &buf) != 0)
2677 int errsv = errno;
2678 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2680 #else
2682 const char *filename = (const gchar *) name->data;
2683 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
2684 int retval;
2685 int save_errno;
2686 int len;
2688 if (wfilename == NULL)
2689 return g_local_file_measure_size_error (state->flags, errno, name, error);
2691 len = wcslen (wfilename);
2692 while (len > 0 && G_IS_DIR_SEPARATOR (wfilename[len-1]))
2693 len--;
2694 if (len > 0 &&
2695 (!g_path_is_absolute (filename) || len > g_path_skip_root (filename) - filename))
2696 wfilename[len] = '\0';
2698 retval = _wstati64 (wfilename, &buf);
2699 save_errno = errno;
2701 g_free (wfilename);
2703 errno = save_errno;
2704 if (retval != 0)
2705 return g_local_file_measure_size_error (state->flags, errno, name, error);
2707 #endif
2709 if (name->next)
2711 /* If not at the toplevel, check for a device boundary. */
2713 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2714 if (state->contained_on != buf.st_dev)
2715 return TRUE;
2717 else
2719 /* If, however, this is the toplevel, set the device number so
2720 * that recursive invocations can compare against it.
2722 state->contained_on = buf.st_dev;
2725 #if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2726 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2727 state->disk_usage += buf.st_blocks * G_GUINT64_CONSTANT (512);
2728 else
2729 #endif
2730 state->disk_usage += buf.st_size;
2732 if (S_ISDIR (buf.st_mode))
2733 state->num_dirs++;
2734 else
2735 state->num_files++;
2737 if (state->progress_callback)
2739 /* We could attempt to do some cleverness here in order to avoid
2740 * calling clock_gettime() so much, but we're doing stats and opens
2741 * all over the place already...
2743 if (state->last_progress_report)
2745 guint64 now;
2747 now = g_get_monotonic_time ();
2749 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2751 (* state->progress_callback) (TRUE,
2752 state->disk_usage, state->num_dirs, state->num_files,
2753 state->progress_data);
2754 state->last_progress_report = now;
2757 else
2759 /* We must do an initial report to inform that more reports
2760 * will be coming.
2762 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2763 state->last_progress_report = g_get_monotonic_time ();
2767 if (S_ISDIR (buf.st_mode))
2769 int dir_fd = -1;
2770 int errsv;
2772 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2773 return FALSE;
2775 #ifdef AT_FDCWD
2776 #ifdef HAVE_OPEN_O_DIRECTORY
2777 dir_fd = openat (parent_fd, name->data, O_RDONLY|O_DIRECTORY);
2778 #else
2779 dir_fd = openat (parent_fd, name->data, O_RDONLY);
2780 #endif
2781 errsv = errno;
2782 if (dir_fd < 0)
2783 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2784 #endif
2786 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2787 return FALSE;
2790 return TRUE;
2793 static gboolean
2794 g_local_file_measure_size_of_contents (gint fd,
2795 GSList *dir_name,
2796 MeasureState *state,
2797 GError **error)
2799 gboolean success = TRUE;
2800 const gchar *name;
2801 GDir *dir;
2803 #ifdef AT_FDCWD
2805 /* If this fails, we want to preserve the errno from fopendir() */
2806 DIR *dirp;
2807 dirp = fdopendir (fd);
2808 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2810 #else
2811 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2812 #endif
2814 if (dir == NULL)
2816 gint saved_errno = errno;
2818 #ifdef AT_FDCWD
2819 close (fd);
2820 #endif
2822 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2825 while (success && (name = g_dir_read_name (dir)))
2827 GSList node;
2829 node.next = dir_name;
2830 #ifdef AT_FDCWD
2831 node.data = (gchar *) name;
2832 #else
2833 node.data = g_build_filename (dir_name->data, name, NULL);
2834 #endif
2836 success = g_local_file_measure_size_of_file (fd, &node, state, error);
2838 #ifndef AT_FDCWD
2839 g_free (node.data);
2840 #endif
2843 g_dir_close (dir);
2845 return success;
2848 static gboolean
2849 g_local_file_measure_disk_usage (GFile *file,
2850 GFileMeasureFlags flags,
2851 GCancellable *cancellable,
2852 GFileMeasureProgressCallback progress_callback,
2853 gpointer progress_data,
2854 guint64 *disk_usage,
2855 guint64 *num_dirs,
2856 guint64 *num_files,
2857 GError **error)
2859 GLocalFile *local_file = G_LOCAL_FILE (file);
2860 MeasureState state = { 0, };
2861 gint root_fd = -1;
2862 GSList node;
2864 state.flags = flags;
2865 state.cancellable = cancellable;
2866 state.progress_callback = progress_callback;
2867 state.progress_data = progress_data;
2869 #ifdef AT_FDCWD
2870 root_fd = AT_FDCWD;
2871 #endif
2873 node.data = local_file->filename;
2874 node.next = NULL;
2876 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
2877 return FALSE;
2879 if (disk_usage)
2880 *disk_usage = state.disk_usage;
2882 if (num_dirs)
2883 *num_dirs = state.num_dirs;
2885 if (num_files)
2886 *num_files = state.num_files;
2888 return TRUE;
2891 static void
2892 g_local_file_file_iface_init (GFileIface *iface)
2894 iface->dup = g_local_file_dup;
2895 iface->hash = g_local_file_hash;
2896 iface->equal = g_local_file_equal;
2897 iface->is_native = g_local_file_is_native;
2898 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2899 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2900 iface->get_basename = g_local_file_get_basename;
2901 iface->get_path = g_local_file_get_path;
2902 iface->get_uri = g_local_file_get_uri;
2903 iface->get_parse_name = g_local_file_get_parse_name;
2904 iface->get_parent = g_local_file_get_parent;
2905 iface->prefix_matches = g_local_file_prefix_matches;
2906 iface->get_relative_path = g_local_file_get_relative_path;
2907 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2908 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2909 iface->set_display_name = g_local_file_set_display_name;
2910 iface->enumerate_children = g_local_file_enumerate_children;
2911 iface->query_info = g_local_file_query_info;
2912 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2913 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2914 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2915 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2916 iface->set_attribute = g_local_file_set_attribute;
2917 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2918 iface->read_fn = g_local_file_read;
2919 iface->append_to = g_local_file_append_to;
2920 iface->create = g_local_file_create;
2921 iface->replace = g_local_file_replace;
2922 iface->open_readwrite = g_local_file_open_readwrite;
2923 iface->create_readwrite = g_local_file_create_readwrite;
2924 iface->replace_readwrite = g_local_file_replace_readwrite;
2925 iface->delete_file = g_local_file_delete;
2926 iface->trash = g_local_file_trash;
2927 iface->make_directory = g_local_file_make_directory;
2928 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2929 iface->copy = g_local_file_copy;
2930 iface->move = g_local_file_move;
2931 iface->monitor_dir = g_local_file_monitor_dir;
2932 iface->monitor_file = g_local_file_monitor_file;
2933 iface->measure_disk_usage = g_local_file_measure_disk_usage;
2935 iface->supports_thread_contexts = TRUE;