Initialize variable
[glib.git] / gio / glocalfile.c
blobe7481454e177839b55d5c11de8cfb975b522c72e
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 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 0x62646576:
669 return "bdevfs";
670 case 0x42465331:
671 return "befs";
672 case 0x1BADFACE:
673 return "bfs";
674 case 0x42494e4d:
675 return "binfmt_misc";
676 case 0x9123683E:
677 return "btrfs";
678 case 0x73727279:
679 return "btrfs_test_fs";
680 case 0x27e0eb:
681 return "cgroup";
682 case 0x63677270:
683 return "cgroup2";
684 case 0xFF534D42:
685 return "cifs";
686 case 0x73757245:
687 return "coda";
688 case 0x012FF7B7:
689 return "coh";
690 case 0x62656570:
691 return "configfs";
692 case 0x28cd3d45:
693 return "cramfs";
694 case 0x64626720:
695 return "debugfs";
696 case 0x1373:
697 return "devfs";
698 case 0x1cd1:
699 return "devpts";
700 case 0xf15f:
701 return "ecryptfs";
702 case 0xde5e81e4:
703 return "efivarfs";
704 case 0x00414A53:
705 return "efs";
706 case 0x137D:
707 return "ext";
708 case 0xEF51:
709 return "ext2";
710 case 0xEF53:
711 return "ext3/ext4";
712 case 0xF2F52010:
713 return "f2fs";
714 case 0x65735546:
715 return "fuse";
716 case 0x65735543:
717 return "fusectl";
718 case 0xBAD1DEA:
719 return "futexfs";
720 case 0x4244:
721 return "hfs";
722 case 0x00c0ffee:
723 return "hostfs";
724 case 0xF995E849:
725 return "hpfs";
726 case 0x958458f6:
727 return "hugetlbfs";
728 case 0x9660:
729 return "isofs";
730 case 0x72b6:
731 return "jffs2";
732 case 0x3153464a:
733 return "jfs";
734 case 0x137F:
735 return "minix";
736 case 0x138F:
737 return "minix2";
738 case 0x2468:
739 return "minix2";
740 case 0x2478:
741 return "minix22";
742 case 0x4d5a:
743 return "minix3";
744 case 0x19800202:
745 return "mqueue";
746 case 0x4d44:
747 return "msdos";
748 case 0x564c:
749 return "ncp";
750 case 0x6969:
751 return "nfs";
752 case 0x3434:
753 return "nilfs";
754 case 0x6e736673:
755 return "nsfs";
756 case 0x5346544e:
757 return "ntfs";
758 case 0x7461636f:
759 return "ocfs2";
760 case 0x9fa1:
761 return "openprom";
762 case 0x794c7630:
763 return "overlay";
764 case 0x50495045:
765 return "pipefs";
766 case 0x9fa0:
767 return "proc";
768 case 0x6165676C:
769 return "pstore";
770 case 0x002f:
771 return "qnx4";
772 case 0x68191122:
773 return "qnx6";
774 case 0x858458f6:
775 return "ramfs";
776 case 0x52654973:
777 return "reiserfs";
778 case 0x7275:
779 return "romfs";
780 case 0x67596969:
781 return "rpc_pipefs";
782 case 0x73636673:
783 return "securityfs";
784 case 0xf97cff8c:
785 return "selinuxfs";
786 case 0x43415d53:
787 return "smackfs";
788 case 0x517B:
789 return "smb";
790 case 0x534F434B:
791 return "sockfs";
792 case 0x73717368:
793 return "squashfs";
794 case 0x62656572:
795 return "sysfs";
796 case 0x012FF7B6:
797 return "sysv2";
798 case 0x012FF7B5:
799 return "sysv4";
800 case 0x01021994:
801 return "tmpfs";
802 case 0x74726163:
803 return "tracefs";
804 case 0x15013346:
805 return "udf";
806 case 0x00011954:
807 return "ufs";
808 case 0x9fa2:
809 return "usbdevice";
810 case 0x01021997:
811 return "v9fs";
812 case 0xa501FCF5:
813 return "vxfs";
814 case 0xabba1974:
815 return "xenfs";
816 case 0x012FF7B4:
817 return "xenix";
818 case 0x58465342:
819 return "xfs";
820 case 0x012FD16D:
821 return "xiafs";
822 case 0x52345362:
823 return "reiser4";
824 default:
825 return NULL;
828 #endif
830 #ifndef G_OS_WIN32
832 G_LOCK_DEFINE_STATIC(mount_info_hash);
833 static GHashTable *mount_info_hash = NULL;
834 static guint64 mount_info_hash_cache_time = 0;
836 typedef enum {
837 MOUNT_INFO_READONLY = 1<<0
838 } MountInfo;
840 static gboolean
841 device_equal (gconstpointer v1,
842 gconstpointer v2)
844 return *(dev_t *)v1 == *(dev_t *)v2;
847 static guint
848 device_hash (gconstpointer v)
850 return (guint) *(dev_t *)v;
853 static void
854 get_mount_info (GFileInfo *fs_info,
855 const char *path,
856 GFileAttributeMatcher *matcher)
858 GStatBuf buf;
859 gboolean got_info;
860 gpointer info_as_ptr;
861 guint mount_info;
862 char *mountpoint;
863 dev_t *dev;
864 GUnixMountEntry *mount;
865 guint64 cache_time;
867 if (g_lstat (path, &buf) != 0)
868 return;
870 G_LOCK (mount_info_hash);
872 if (mount_info_hash == NULL)
873 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
874 g_free, NULL);
877 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
878 g_hash_table_remove_all (mount_info_hash);
880 got_info = g_hash_table_lookup_extended (mount_info_hash,
881 &buf.st_dev,
882 NULL,
883 &info_as_ptr);
885 G_UNLOCK (mount_info_hash);
887 mount_info = GPOINTER_TO_UINT (info_as_ptr);
889 if (!got_info)
891 mount_info = 0;
893 mountpoint = find_mountpoint_for (path, buf.st_dev);
894 if (mountpoint == NULL)
895 mountpoint = g_strdup ("/");
897 mount = g_unix_mount_at (mountpoint, &cache_time);
898 if (mount)
900 if (g_unix_mount_is_readonly (mount))
901 mount_info |= MOUNT_INFO_READONLY;
903 g_unix_mount_free (mount);
906 g_free (mountpoint);
908 dev = g_new0 (dev_t, 1);
909 *dev = buf.st_dev;
911 G_LOCK (mount_info_hash);
912 mount_info_hash_cache_time = cache_time;
913 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
914 G_UNLOCK (mount_info_hash);
917 if (mount_info & MOUNT_INFO_READONLY)
918 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
921 #endif
923 #ifdef G_OS_WIN32
925 static gboolean
926 is_xp_or_later (void)
928 static int result = -1;
930 if (result == -1)
932 #ifndef _MSC_VER
933 OSVERSIONINFOEX ver_info = {0};
934 DWORDLONG cond_mask = 0;
935 int op = VER_GREATER_EQUAL;
937 ver_info.dwOSVersionInfoSize = sizeof ver_info;
938 ver_info.dwMajorVersion = 5;
939 ver_info.dwMinorVersion = 1;
941 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
942 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
944 result = VerifyVersionInfo (&ver_info,
945 VER_MAJORVERSION | VER_MINORVERSION,
946 cond_mask) != 0;
947 #else
948 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
949 #endif
952 return result;
955 static wchar_t *
956 get_volume_for_path (const char *path)
958 long len;
959 wchar_t *wpath;
960 wchar_t *result;
962 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
963 result = g_new (wchar_t, MAX_PATH);
965 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
967 char *msg = g_win32_error_message (GetLastError ());
968 g_critical ("GetVolumePathName failed: %s", msg);
969 g_free (msg);
970 g_free (result);
971 g_free (wpath);
972 return NULL;
975 len = wcslen (result);
976 if (len > 0 && result[len-1] != L'\\')
978 result = g_renew (wchar_t, result, len + 2);
979 result[len] = L'\\';
980 result[len + 1] = 0;
983 g_free (wpath);
984 return result;
987 static char *
988 find_mountpoint_for (const char *file, dev_t dev)
990 wchar_t *wpath;
991 char *utf8_path;
993 wpath = get_volume_for_path (file);
994 if (!wpath)
995 return NULL;
997 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
999 g_free (wpath);
1000 return utf8_path;
1003 static void
1004 get_filesystem_readonly (GFileInfo *info,
1005 const char *path)
1007 wchar_t *rootdir;
1009 rootdir = get_volume_for_path (path);
1011 if (rootdir)
1013 if (is_xp_or_later ())
1015 DWORD flags;
1016 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
1017 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
1018 (flags & FILE_READ_ONLY_VOLUME) != 0);
1020 else
1022 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
1023 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
1027 g_free (rootdir);
1030 #endif /* G_OS_WIN32 */
1032 #pragma GCC diagnostic push
1033 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1034 static void
1035 g_set_io_error (GError **error,
1036 const gchar *msg,
1037 GFile *file,
1038 gint errsv)
1040 GLocalFile *local = G_LOCAL_FILE (file);
1041 gchar *display_name;
1043 display_name = g_filename_display_name (local->filename);
1044 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1045 msg, display_name, g_strerror (errsv));
1046 g_free (display_name);
1048 #pragma GCC diagnostic pop
1050 static GFileInfo *
1051 g_local_file_query_filesystem_info (GFile *file,
1052 const char *attributes,
1053 GCancellable *cancellable,
1054 GError **error)
1056 GLocalFile *local = G_LOCAL_FILE (file);
1057 GFileInfo *info;
1058 int statfs_result = 0;
1059 gboolean no_size;
1060 #ifndef G_OS_WIN32
1061 const char *fstype;
1062 #ifdef USE_STATFS
1063 guint64 block_size;
1064 struct statfs statfs_buffer;
1065 #elif defined(USE_STATVFS)
1066 guint64 block_size;
1067 struct statvfs statfs_buffer;
1068 #endif /* USE_STATFS */
1069 #endif /* G_OS_WIN32 */
1070 GFileAttributeMatcher *attribute_matcher;
1072 no_size = FALSE;
1074 #ifdef USE_STATFS
1076 #if STATFS_ARGS == 2
1077 statfs_result = statfs (local->filename, &statfs_buffer);
1078 #elif STATFS_ARGS == 4
1079 statfs_result = statfs (local->filename, &statfs_buffer,
1080 sizeof (statfs_buffer), 0);
1081 #endif /* STATFS_ARGS == 2 */
1082 block_size = statfs_buffer.f_bsize;
1084 /* Many backends can't report free size (for instance the gvfs fuse
1085 backend for backend not supporting this), and set f_bfree to 0,
1086 but it can be 0 for real too. We treat the available == 0 and
1087 free == 0 case as "both of these are invalid".
1089 #ifndef G_OS_WIN32
1090 if (statfs_result == 0 &&
1091 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
1092 no_size = TRUE;
1093 #endif /* G_OS_WIN32 */
1095 #elif defined(USE_STATVFS)
1096 statfs_result = statvfs (local->filename, &statfs_buffer);
1097 block_size = statfs_buffer.f_frsize;
1098 #endif /* USE_STATFS */
1100 if (statfs_result == -1)
1102 int errsv = errno;
1104 g_set_io_error (error,
1105 _("Error getting filesystem info for %s: %s"),
1106 file, errsv);
1107 return NULL;
1110 info = g_file_info_new ();
1112 attribute_matcher = g_file_attribute_matcher_new (attributes);
1114 if (!no_size &&
1115 g_file_attribute_matcher_matches (attribute_matcher,
1116 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1118 #ifdef G_OS_WIN32
1119 gchar *localdir = g_path_get_dirname (local->filename);
1120 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1121 ULARGE_INTEGER li;
1123 g_free (localdir);
1124 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1125 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1126 g_free (wdirname);
1127 #else
1128 #if defined(USE_STATFS) || defined(USE_STATVFS)
1129 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1130 #endif
1131 #endif
1133 if (!no_size &&
1134 g_file_attribute_matcher_matches (attribute_matcher,
1135 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1137 #ifdef G_OS_WIN32
1138 gchar *localdir = g_path_get_dirname (local->filename);
1139 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1140 ULARGE_INTEGER li;
1142 g_free (localdir);
1143 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1144 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1145 g_free (wdirname);
1146 #else
1147 #if defined(USE_STATFS) || defined(USE_STATVFS)
1148 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1149 #endif
1150 #endif /* G_OS_WIN32 */
1153 if (!no_size &&
1154 g_file_attribute_matcher_matches (attribute_matcher,
1155 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1157 #ifdef G_OS_WIN32
1158 gchar *localdir = g_path_get_dirname (local->filename);
1159 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1160 ULARGE_INTEGER li_free;
1161 ULARGE_INTEGER li_total;
1163 g_free (localdir);
1164 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1165 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1166 g_free (wdirname);
1167 #else
1168 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1169 #endif /* G_OS_WIN32 */
1172 #ifndef G_OS_WIN32
1173 #ifdef USE_STATFS
1174 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1175 fstype = statfs_buffer.f_fstypename;
1176 #else
1177 fstype = get_fs_type (statfs_buffer.f_type);
1178 #endif
1180 #elif defined(USE_STATVFS)
1181 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1182 fstype = statfs_buffer.f_fstypename;
1183 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1184 fstype = statfs_buffer.f_basetype;
1185 #else
1186 fstype = NULL;
1187 #endif
1188 #endif /* USE_STATFS */
1190 if (fstype &&
1191 g_file_attribute_matcher_matches (attribute_matcher,
1192 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1193 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1194 #endif /* G_OS_WIN32 */
1196 if (g_file_attribute_matcher_matches (attribute_matcher,
1197 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1199 #ifdef G_OS_WIN32
1200 get_filesystem_readonly (info, local->filename);
1201 #else
1202 get_mount_info (info, local->filename, attribute_matcher);
1203 #endif /* G_OS_WIN32 */
1206 if (g_file_attribute_matcher_matches (attribute_matcher,
1207 G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
1208 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE,
1209 g_local_file_is_remote (local->filename));
1211 g_file_attribute_matcher_unref (attribute_matcher);
1213 return info;
1216 static GMount *
1217 g_local_file_find_enclosing_mount (GFile *file,
1218 GCancellable *cancellable,
1219 GError **error)
1221 GLocalFile *local = G_LOCAL_FILE (file);
1222 GStatBuf buf;
1223 char *mountpoint;
1224 GMount *mount;
1226 if (g_lstat (local->filename, &buf) != 0)
1227 goto error;
1229 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1230 if (mountpoint == NULL)
1231 goto error;
1233 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1234 g_free (mountpoint);
1235 if (mount)
1236 return mount;
1238 error:
1239 g_set_io_error (error,
1240 /* Translators: This is an error message when trying to find
1241 * the enclosing (user visible) mount of a file, but none
1242 * exists.
1244 _("Containing mount for file %s not found"),
1245 file, 0);
1247 return NULL;
1250 static GFile *
1251 g_local_file_set_display_name (GFile *file,
1252 const char *display_name,
1253 GCancellable *cancellable,
1254 GError **error)
1256 GLocalFile *local, *new_local;
1257 GFile *new_file, *parent;
1258 GStatBuf statbuf;
1259 GVfsClass *class;
1260 GVfs *vfs;
1261 int errsv;
1263 parent = g_file_get_parent (file);
1264 if (parent == NULL)
1266 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1267 _("Can’t rename root directory"));
1268 return NULL;
1271 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1272 g_object_unref (parent);
1274 if (new_file == NULL)
1275 return NULL;
1276 local = G_LOCAL_FILE (file);
1277 new_local = G_LOCAL_FILE (new_file);
1279 if (g_lstat (new_local->filename, &statbuf) == -1)
1281 errsv = errno;
1283 if (errsv != ENOENT)
1285 g_set_io_error (error, _("Error renaming file %s: %s"), new_file, errsv);
1286 return NULL;
1289 else
1291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
1292 _("Can’t rename file, filename already exists"));
1293 return NULL;
1296 if (g_rename (local->filename, new_local->filename) == -1)
1298 errsv = errno;
1300 if (errsv == EINVAL)
1301 /* We can't get a rename file into itself error here,
1302 * so this must be an invalid filename, on e.g. FAT
1304 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME,
1305 _("Invalid filename"));
1306 else
1307 g_set_io_error (error,
1308 _("Error renaming file %s: %s"),
1309 file, errsv);
1310 g_object_unref (new_file);
1311 return NULL;
1314 vfs = g_vfs_get_default ();
1315 class = G_VFS_GET_CLASS (vfs);
1316 if (class->local_file_moved)
1317 class->local_file_moved (vfs, local->filename, new_local->filename);
1319 return new_file;
1322 static GFileInfo *
1323 g_local_file_query_info (GFile *file,
1324 const char *attributes,
1325 GFileQueryInfoFlags flags,
1326 GCancellable *cancellable,
1327 GError **error)
1329 GLocalFile *local = G_LOCAL_FILE (file);
1330 GFileInfo *info;
1331 GFileAttributeMatcher *matcher;
1332 char *basename, *dirname;
1333 GLocalParentFileInfo parent_info;
1335 matcher = g_file_attribute_matcher_new (attributes);
1337 basename = g_path_get_basename (local->filename);
1339 dirname = g_path_get_dirname (local->filename);
1340 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1341 g_free (dirname);
1343 info = _g_local_file_info_get (basename, local->filename,
1344 matcher, flags, &parent_info,
1345 error);
1348 _g_local_file_info_free_parent_info (&parent_info);
1349 g_free (basename);
1351 g_file_attribute_matcher_unref (matcher);
1353 return info;
1356 static GFileAttributeInfoList *
1357 g_local_file_query_settable_attributes (GFile *file,
1358 GCancellable *cancellable,
1359 GError **error)
1361 return g_file_attribute_info_list_ref (local_writable_attributes);
1364 static GFileAttributeInfoList *
1365 g_local_file_query_writable_namespaces (GFile *file,
1366 GCancellable *cancellable,
1367 GError **error)
1369 GFileAttributeInfoList *list;
1370 GVfsClass *class;
1371 GVfs *vfs;
1373 if (g_once_init_enter (&local_writable_namespaces))
1375 /* Writable namespaces: */
1377 list = g_file_attribute_info_list_new ();
1379 #ifdef HAVE_XATTR
1380 g_file_attribute_info_list_add (list,
1381 "xattr",
1382 G_FILE_ATTRIBUTE_TYPE_STRING,
1383 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1384 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1385 g_file_attribute_info_list_add (list,
1386 "xattr-sys",
1387 G_FILE_ATTRIBUTE_TYPE_STRING,
1388 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1389 #endif
1391 vfs = g_vfs_get_default ();
1392 class = G_VFS_GET_CLASS (vfs);
1393 if (class->add_writable_namespaces)
1394 class->add_writable_namespaces (vfs, list);
1396 g_once_init_leave (&local_writable_namespaces, (gsize)list);
1398 list = (GFileAttributeInfoList *)local_writable_namespaces;
1400 return g_file_attribute_info_list_ref (list);
1403 static gboolean
1404 g_local_file_set_attribute (GFile *file,
1405 const char *attribute,
1406 GFileAttributeType type,
1407 gpointer value_p,
1408 GFileQueryInfoFlags flags,
1409 GCancellable *cancellable,
1410 GError **error)
1412 GLocalFile *local = G_LOCAL_FILE (file);
1414 return _g_local_file_info_set_attribute (local->filename,
1415 attribute,
1416 type,
1417 value_p,
1418 flags,
1419 cancellable,
1420 error);
1423 static gboolean
1424 g_local_file_set_attributes_from_info (GFile *file,
1425 GFileInfo *info,
1426 GFileQueryInfoFlags flags,
1427 GCancellable *cancellable,
1428 GError **error)
1430 GLocalFile *local = G_LOCAL_FILE (file);
1431 int res, chained_res;
1432 GFileIface *default_iface;
1434 res = _g_local_file_info_set_attributes (local->filename,
1435 info, flags,
1436 cancellable,
1437 error);
1439 if (!res)
1440 error = NULL; /* Don't write over error if further errors */
1442 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1444 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1446 return res && chained_res;
1449 static GFileInputStream *
1450 g_local_file_read (GFile *file,
1451 GCancellable *cancellable,
1452 GError **error)
1454 GLocalFile *local = G_LOCAL_FILE (file);
1455 int fd, ret;
1456 GLocalFileStat buf;
1458 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1459 if (fd == -1)
1461 int errsv = errno;
1463 #ifdef G_OS_WIN32
1464 if (errsv == EACCES)
1466 /* Exploit the fact that on W32 the glib filename encoding is UTF8 */
1467 ret = GLIB_PRIVATE_CALL (g_win32_stat_utf8) (local->filename, &buf);
1468 if (ret == 0 && S_ISDIR (buf.st_mode))
1469 errsv = EISDIR;
1471 #endif
1472 g_set_io_error (error,
1473 _("Error opening file %s: %s"),
1474 file, errsv);
1475 return NULL;
1478 #ifdef G_OS_WIN32
1479 ret = GLIB_PRIVATE_CALL (g_win32_fstat) (fd, &buf);
1480 #else
1481 ret = fstat (fd, &buf);
1482 #endif
1484 if (ret == 0 && S_ISDIR (buf.st_mode))
1486 (void) g_close (fd, NULL);
1487 g_set_io_error (error,
1488 _("Error opening file %s: %s"),
1489 file, EISDIR);
1490 return NULL;
1493 return _g_local_file_input_stream_new (fd);
1496 static GFileOutputStream *
1497 g_local_file_append_to (GFile *file,
1498 GFileCreateFlags flags,
1499 GCancellable *cancellable,
1500 GError **error)
1502 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1503 flags, cancellable, error);
1506 static GFileOutputStream *
1507 g_local_file_create (GFile *file,
1508 GFileCreateFlags flags,
1509 GCancellable *cancellable,
1510 GError **error)
1512 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1513 FALSE, flags, NULL,
1514 cancellable, error);
1517 static GFileOutputStream *
1518 g_local_file_replace (GFile *file,
1519 const char *etag,
1520 gboolean make_backup,
1521 GFileCreateFlags flags,
1522 GCancellable *cancellable,
1523 GError **error)
1525 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1526 FALSE,
1527 etag, make_backup, flags, NULL,
1528 cancellable, error);
1531 static GFileIOStream *
1532 g_local_file_open_readwrite (GFile *file,
1533 GCancellable *cancellable,
1534 GError **error)
1536 GFileOutputStream *output;
1537 GFileIOStream *res;
1539 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1540 TRUE,
1541 cancellable, error);
1542 if (output == NULL)
1543 return NULL;
1545 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1546 g_object_unref (output);
1547 return res;
1550 static GFileIOStream *
1551 g_local_file_create_readwrite (GFile *file,
1552 GFileCreateFlags flags,
1553 GCancellable *cancellable,
1554 GError **error)
1556 GFileOutputStream *output;
1557 GFileIOStream *res;
1559 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1560 TRUE, flags, NULL,
1561 cancellable, error);
1562 if (output == NULL)
1563 return NULL;
1565 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1566 g_object_unref (output);
1567 return res;
1570 static GFileIOStream *
1571 g_local_file_replace_readwrite (GFile *file,
1572 const char *etag,
1573 gboolean make_backup,
1574 GFileCreateFlags flags,
1575 GCancellable *cancellable,
1576 GError **error)
1578 GFileOutputStream *output;
1579 GFileIOStream *res;
1581 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1582 TRUE,
1583 etag, make_backup, flags, NULL,
1584 cancellable, error);
1585 if (output == NULL)
1586 return NULL;
1588 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1589 g_object_unref (output);
1590 return res;
1593 static gboolean
1594 g_local_file_delete (GFile *file,
1595 GCancellable *cancellable,
1596 GError **error)
1598 GLocalFile *local = G_LOCAL_FILE (file);
1599 GVfsClass *class;
1600 GVfs *vfs;
1602 if (g_remove (local->filename) == -1)
1604 int errsv = errno;
1606 /* Posix allows EEXIST too, but the more sane error
1607 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1608 expects */
1609 if (errsv == EEXIST)
1610 errsv = ENOTEMPTY;
1612 g_set_io_error (error,
1613 _("Error removing file %s: %s"),
1614 file, errsv);
1615 return FALSE;
1618 vfs = g_vfs_get_default ();
1619 class = G_VFS_GET_CLASS (vfs);
1620 if (class->local_file_removed)
1621 class->local_file_removed (vfs, local->filename);
1623 return TRUE;
1626 #ifndef G_OS_WIN32
1628 static char *
1629 strip_trailing_slashes (const char *path)
1631 char *path_copy;
1632 int len;
1634 path_copy = g_strdup (path);
1635 len = strlen (path_copy);
1636 while (len > 1 && path_copy[len-1] == '/')
1637 path_copy[--len] = 0;
1639 return path_copy;
1642 static char *
1643 expand_symlink (const char *link)
1645 char *resolved, *canonical, *parent, *link2;
1646 char symlink_value[4096];
1647 #ifdef G_OS_WIN32
1648 #else
1649 gssize res;
1650 #endif
1652 #ifdef G_OS_WIN32
1653 #else
1654 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1656 if (res == -1)
1657 return g_strdup (link);
1658 symlink_value[res] = 0;
1659 #endif
1661 if (g_path_is_absolute (symlink_value))
1662 return canonicalize_filename (symlink_value);
1663 else
1665 link2 = strip_trailing_slashes (link);
1666 parent = g_path_get_dirname (link2);
1667 g_free (link2);
1669 resolved = g_build_filename (parent, symlink_value, NULL);
1670 g_free (parent);
1672 canonical = canonicalize_filename (resolved);
1674 g_free (resolved);
1676 return canonical;
1680 static char *
1681 get_parent (const char *path,
1682 dev_t *parent_dev)
1684 char *parent, *tmp;
1685 GStatBuf parent_stat;
1686 int num_recursions;
1687 char *path_copy;
1689 path_copy = strip_trailing_slashes (path);
1691 parent = g_path_get_dirname (path_copy);
1692 if (strcmp (parent, ".") == 0 ||
1693 strcmp (parent, path_copy) == 0)
1695 g_free (parent);
1696 g_free (path_copy);
1697 return NULL;
1699 g_free (path_copy);
1701 num_recursions = 0;
1702 do {
1703 if (g_lstat (parent, &parent_stat) != 0)
1705 g_free (parent);
1706 return NULL;
1709 if (S_ISLNK (parent_stat.st_mode))
1711 tmp = parent;
1712 parent = expand_symlink (parent);
1713 g_free (tmp);
1716 num_recursions++;
1717 if (num_recursions > 12)
1719 g_free (parent);
1720 return NULL;
1722 } while (S_ISLNK (parent_stat.st_mode));
1724 *parent_dev = parent_stat.st_dev;
1726 return parent;
1729 static char *
1730 expand_all_symlinks (const char *path)
1732 char *parent, *parent_expanded;
1733 char *basename, *res;
1734 dev_t parent_dev;
1736 parent = get_parent (path, &parent_dev);
1737 if (parent)
1739 parent_expanded = expand_all_symlinks (parent);
1740 g_free (parent);
1741 basename = g_path_get_basename (path);
1742 res = g_build_filename (parent_expanded, basename, NULL);
1743 g_free (basename);
1744 g_free (parent_expanded);
1746 else
1747 res = g_strdup (path);
1749 return res;
1752 static char *
1753 find_mountpoint_for (const char *file,
1754 dev_t dev)
1756 char *dir, *parent;
1757 dev_t dir_dev, parent_dev;
1759 dir = g_strdup (file);
1760 dir_dev = dev;
1762 while (1)
1764 parent = get_parent (dir, &parent_dev);
1765 if (parent == NULL)
1766 return dir;
1768 if (parent_dev != dir_dev)
1770 g_free (parent);
1771 return dir;
1774 g_free (dir);
1775 dir = parent;
1779 char *
1780 _g_local_file_find_topdir_for (const char *file)
1782 char *dir;
1783 char *mountpoint = NULL;
1784 dev_t dir_dev;
1786 dir = get_parent (file, &dir_dev);
1787 if (dir == NULL)
1788 return NULL;
1790 mountpoint = find_mountpoint_for (dir, dir_dev);
1791 g_free (dir);
1793 return mountpoint;
1796 static char *
1797 get_unique_filename (const char *basename,
1798 int id)
1800 const char *dot;
1802 if (id == 1)
1803 return g_strdup (basename);
1805 dot = strchr (basename, '.');
1806 if (dot)
1807 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1808 else
1809 return g_strdup_printf ("%s.%d", basename, id);
1812 static gboolean
1813 path_has_prefix (const char *path,
1814 const char *prefix)
1816 int prefix_len;
1818 if (prefix == NULL)
1819 return TRUE;
1821 prefix_len = strlen (prefix);
1823 if (strncmp (path, prefix, prefix_len) == 0 &&
1824 (prefix_len == 0 || /* empty prefix always matches */
1825 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1826 path[prefix_len] == 0 ||
1827 path[prefix_len] == '/'))
1828 return TRUE;
1830 return FALSE;
1833 static char *
1834 try_make_relative (const char *path,
1835 const char *base)
1837 char *path2, *base2;
1838 char *relative;
1840 path2 = expand_all_symlinks (path);
1841 base2 = expand_all_symlinks (base);
1843 relative = NULL;
1844 if (path_has_prefix (path2, base2))
1846 relative = path2 + strlen (base2);
1847 while (*relative == '/')
1848 relative ++;
1849 relative = g_strdup (relative);
1851 g_free (path2);
1852 g_free (base2);
1854 if (relative)
1855 return relative;
1857 /* Failed, use abs path */
1858 return g_strdup (path);
1861 gboolean
1862 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1864 static gsize home_dev_set = 0;
1865 static dev_t home_dev;
1866 char *topdir, *globaldir, *trashdir, *tmpname;
1867 uid_t uid;
1868 char uid_str[32];
1869 GStatBuf global_stat, trash_stat;
1870 gboolean res;
1872 if (g_once_init_enter (&home_dev_set))
1874 GStatBuf home_stat;
1876 g_stat (g_get_home_dir (), &home_stat);
1877 home_dev = home_stat.st_dev;
1878 g_once_init_leave (&home_dev_set, 1);
1881 /* Assume we can trash to the home */
1882 if (dir_dev == home_dev)
1883 return TRUE;
1885 topdir = find_mountpoint_for (dirname, dir_dev);
1886 if (topdir == NULL)
1887 return FALSE;
1889 globaldir = g_build_filename (topdir, ".Trash", NULL);
1890 if (g_lstat (globaldir, &global_stat) == 0 &&
1891 S_ISDIR (global_stat.st_mode) &&
1892 (global_stat.st_mode & S_ISVTX) != 0)
1894 /* got a toplevel sysadmin created dir, assume we
1895 * can trash to it (we should be able to create a dir)
1896 * This fails for the FAT case where the ownership of
1897 * that dir would be wrong though..
1899 g_free (globaldir);
1900 g_free (topdir);
1901 return TRUE;
1903 g_free (globaldir);
1905 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1906 uid = geteuid ();
1907 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1909 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1910 trashdir = g_build_filename (topdir, tmpname, NULL);
1911 g_free (tmpname);
1913 if (g_lstat (trashdir, &trash_stat) == 0)
1915 g_free (topdir);
1916 g_free (trashdir);
1917 return S_ISDIR (trash_stat.st_mode) &&
1918 trash_stat.st_uid == uid;
1920 g_free (trashdir);
1922 /* User specific trash didn't exist, can we create it? */
1923 res = g_access (topdir, W_OK) == 0;
1924 g_free (topdir);
1926 return res;
1929 #ifdef G_OS_UNIX
1930 gboolean
1931 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1933 gboolean ret = FALSE;
1934 gchar *mount_dir = NULL;
1935 size_t mount_dir_len;
1936 GStatBuf statbuf;
1938 if (!g_str_has_suffix (path, "/lost+found"))
1939 goto out;
1941 mount_dir = find_mountpoint_for (path, path_dev);
1942 if (mount_dir == NULL)
1943 goto out;
1945 mount_dir_len = strlen (mount_dir);
1946 /* We special-case rootfs ('/') since it's the only case where
1947 * mount_dir ends in '/'
1949 if (mount_dir_len == 1)
1950 mount_dir_len--;
1951 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1952 goto out;
1954 if (g_lstat (path, &statbuf) != 0)
1955 goto out;
1957 if (!(S_ISDIR (statbuf.st_mode) &&
1958 statbuf.st_uid == 0 &&
1959 statbuf.st_gid == 0))
1960 goto out;
1962 ret = TRUE;
1964 out:
1965 g_free (mount_dir);
1966 return ret;
1968 #endif
1970 static gboolean
1971 g_local_file_trash (GFile *file,
1972 GCancellable *cancellable,
1973 GError **error)
1975 GLocalFile *local = G_LOCAL_FILE (file);
1976 GStatBuf file_stat, home_stat;
1977 const char *homedir;
1978 char *trashdir, *topdir, *infodir, *filesdir;
1979 char *basename, *trashname, *trashfile, *infoname, *infofile;
1980 char *original_name, *original_name_escaped;
1981 int i;
1982 char *data;
1983 gboolean is_homedir_trash;
1984 char delete_time[32];
1985 int fd;
1986 GStatBuf trash_stat, global_stat;
1987 char *dirname, *globaldir;
1988 GVfsClass *class;
1989 GVfs *vfs;
1990 int errsv;
1992 if (g_lstat (local->filename, &file_stat) != 0)
1994 errsv = errno;
1996 g_set_io_error (error,
1997 _("Error trashing file %s: %s"),
1998 file, errsv);
1999 return FALSE;
2002 homedir = g_get_home_dir ();
2003 g_stat (homedir, &home_stat);
2005 is_homedir_trash = FALSE;
2006 trashdir = NULL;
2007 if (file_stat.st_dev == home_stat.st_dev)
2009 is_homedir_trash = TRUE;
2010 errno = 0;
2011 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
2012 if (g_mkdir_with_parents (trashdir, 0700) < 0)
2014 char *display_name;
2015 errsv = errno;
2017 display_name = g_filename_display_name (trashdir);
2018 g_set_error (error, G_IO_ERROR,
2019 g_io_error_from_errno (errsv),
2020 _("Unable to create trash dir %s: %s"),
2021 display_name, g_strerror (errsv));
2022 g_free (display_name);
2023 g_free (trashdir);
2024 return FALSE;
2026 topdir = g_strdup (g_get_user_data_dir ());
2028 else
2030 uid_t uid;
2031 char uid_str[32];
2033 uid = geteuid ();
2034 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
2036 topdir = _g_local_file_find_topdir_for (local->filename);
2037 if (topdir == NULL)
2039 g_set_io_error (error,
2040 _("Unable to find toplevel directory to trash %s"),
2041 file, G_IO_ERROR_NOT_SUPPORTED);
2042 return FALSE;
2045 /* Try looking for global trash dir $topdir/.Trash/$uid */
2046 globaldir = g_build_filename (topdir, ".Trash", NULL);
2047 if (g_lstat (globaldir, &global_stat) == 0 &&
2048 S_ISDIR (global_stat.st_mode) &&
2049 (global_stat.st_mode & S_ISVTX) != 0)
2051 trashdir = g_build_filename (globaldir, uid_str, NULL);
2053 if (g_lstat (trashdir, &trash_stat) == 0)
2055 if (!S_ISDIR (trash_stat.st_mode) ||
2056 trash_stat.st_uid != uid)
2058 /* Not a directory or not owned by user, ignore */
2059 g_free (trashdir);
2060 trashdir = NULL;
2063 else if (g_mkdir (trashdir, 0700) == -1)
2065 g_free (trashdir);
2066 trashdir = NULL;
2069 g_free (globaldir);
2071 if (trashdir == NULL)
2073 gboolean tried_create;
2075 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2076 dirname = g_strdup_printf (".Trash-%s", uid_str);
2077 trashdir = g_build_filename (topdir, dirname, NULL);
2078 g_free (dirname);
2080 tried_create = FALSE;
2082 retry:
2083 if (g_lstat (trashdir, &trash_stat) == 0)
2085 if (!S_ISDIR (trash_stat.st_mode) ||
2086 trash_stat.st_uid != uid)
2088 /* Remove the failed directory */
2089 if (tried_create)
2090 g_remove (trashdir);
2092 /* Not a directory or not owned by user, ignore */
2093 g_free (trashdir);
2094 trashdir = NULL;
2097 else
2099 if (!tried_create &&
2100 g_mkdir (trashdir, 0700) != -1)
2102 /* Ensure that the created dir has the right uid etc.
2103 This might fail on e.g. a FAT dir */
2104 tried_create = TRUE;
2105 goto retry;
2107 else
2109 g_free (trashdir);
2110 trashdir = NULL;
2115 if (trashdir == NULL)
2117 g_free (topdir);
2118 g_set_io_error (error,
2119 _("Unable to find or create trash directory for %s"),
2120 file, G_IO_ERROR_NOT_SUPPORTED);
2121 return FALSE;
2125 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2127 infodir = g_build_filename (trashdir, "info", NULL);
2128 filesdir = g_build_filename (trashdir, "files", NULL);
2129 g_free (trashdir);
2131 /* Make sure we have the subdirectories */
2132 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2133 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2135 g_free (topdir);
2136 g_free (infodir);
2137 g_free (filesdir);
2138 g_set_io_error (error,
2139 _("Unable to find or create trash directory for %s"),
2140 file, G_IO_ERROR_NOT_SUPPORTED);
2141 return FALSE;
2144 basename = g_path_get_basename (local->filename);
2145 i = 1;
2146 trashname = NULL;
2147 infofile = NULL;
2148 do {
2149 g_free (trashname);
2150 g_free (infofile);
2152 trashname = get_unique_filename (basename, i++);
2153 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2154 infofile = g_build_filename (infodir, infoname, NULL);
2155 g_free (infoname);
2157 fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
2158 errsv = errno;
2159 } while (fd == -1 && errsv == EEXIST);
2161 g_free (basename);
2162 g_free (infodir);
2164 if (fd == -1)
2166 errsv = errno;
2168 g_free (filesdir);
2169 g_free (topdir);
2170 g_free (trashname);
2171 g_free (infofile);
2173 g_set_io_error (error,
2174 _("Unable to create trashing info file for %s: %s"),
2175 file, errsv);
2176 return FALSE;
2179 (void) g_close (fd, NULL);
2181 /* Write the full content of the info file before trashing to make
2182 * sure someone doesn't read an empty file. See #749314
2185 /* Use absolute names for homedir */
2186 if (is_homedir_trash)
2187 original_name = g_strdup (local->filename);
2188 else
2189 original_name = try_make_relative (local->filename, topdir);
2190 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2192 g_free (original_name);
2193 g_free (topdir);
2196 time_t t;
2197 struct tm now;
2198 t = time (NULL);
2199 localtime_r (&t, &now);
2200 delete_time[0] = 0;
2201 strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
2204 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2205 original_name_escaped, delete_time);
2207 g_file_set_contents (infofile, data, -1, NULL);
2209 /* TODO: Maybe we should verify that you can delete the file from the trash
2210 * before moving it? OTOH, that is hard, as it needs a recursive scan
2213 trashfile = g_build_filename (filesdir, trashname, NULL);
2215 g_free (filesdir);
2217 if (g_rename (local->filename, trashfile) == -1)
2219 errsv = errno;
2221 g_unlink (infofile);
2223 g_free (trashname);
2224 g_free (infofile);
2225 g_free (trashfile);
2227 if (errsv == EXDEV)
2228 /* The trash dir was actually on another fs anyway!?
2229 * This can happen when the same device is mounted multiple
2230 * times, or with bind mounts of the same fs.
2232 g_set_io_error (error,
2233 _("Unable to trash file %s across filesystem boundaries"),
2234 file, ENOTSUP);
2235 else
2236 g_set_io_error (error,
2237 _("Unable to trash file %s: %s"),
2238 file, errsv);
2239 return FALSE;
2242 vfs = g_vfs_get_default ();
2243 class = G_VFS_GET_CLASS (vfs);
2244 if (class->local_file_moved)
2245 class->local_file_moved (vfs, local->filename, trashfile);
2247 g_free (trashfile);
2249 /* TODO: Do we need to update mtime/atime here after the move? */
2251 g_free (infofile);
2252 g_free (data);
2254 g_free (original_name_escaped);
2255 g_free (trashname);
2257 return TRUE;
2259 #else /* G_OS_WIN32 */
2260 gboolean
2261 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2263 return FALSE; /* XXX ??? */
2266 static gboolean
2267 g_local_file_trash (GFile *file,
2268 GCancellable *cancellable,
2269 GError **error)
2271 GLocalFile *local = G_LOCAL_FILE (file);
2272 SHFILEOPSTRUCTW op = {0};
2273 gboolean success;
2274 wchar_t *wfilename;
2275 long len;
2277 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2278 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2279 wfilename = g_renew (wchar_t, wfilename, len + 2);
2280 wfilename[len + 1] = 0;
2282 op.wFunc = FO_DELETE;
2283 op.pFrom = wfilename;
2284 op.fFlags = FOF_ALLOWUNDO;
2286 success = SHFileOperationW (&op) == 0;
2288 if (success && op.fAnyOperationsAborted)
2290 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2291 g_cancellable_cancel (cancellable);
2292 g_set_io_error (error,
2293 _("Unable to trash file %s: %s"),
2294 file, ECANCELED);
2295 success = FALSE;
2297 else if (!success)
2298 g_set_io_error (error,
2299 _("Unable to trash file %s"),
2300 file, 0);
2302 g_free (wfilename);
2303 return success;
2305 #endif /* G_OS_WIN32 */
2307 static gboolean
2308 g_local_file_make_directory (GFile *file,
2309 GCancellable *cancellable,
2310 GError **error)
2312 GLocalFile *local = G_LOCAL_FILE (file);
2314 if (g_mkdir (local->filename, 0777) == -1)
2316 int errsv = errno;
2318 if (errsv == EINVAL)
2319 /* This must be an invalid filename, on e.g. FAT */
2320 g_set_error_literal (error, G_IO_ERROR,
2321 G_IO_ERROR_INVALID_FILENAME,
2322 _("Invalid filename"));
2323 else
2324 g_set_io_error (error,
2325 _("Error creating directory %s: %s"),
2326 file, errsv);
2327 return FALSE;
2330 return TRUE;
2333 static gboolean
2334 g_local_file_make_symbolic_link (GFile *file,
2335 const char *symlink_value,
2336 GCancellable *cancellable,
2337 GError **error)
2339 #ifdef HAVE_SYMLINK
2340 GLocalFile *local = G_LOCAL_FILE (file);
2342 if (symlink (symlink_value, local->filename) == -1)
2344 int errsv = errno;
2346 if (errsv == EINVAL)
2347 /* This must be an invalid filename, on e.g. FAT */
2348 g_set_error_literal (error, G_IO_ERROR,
2349 G_IO_ERROR_INVALID_FILENAME,
2350 _("Invalid filename"));
2351 else if (errsv == EPERM)
2352 g_set_error (error, G_IO_ERROR,
2353 G_IO_ERROR_NOT_SUPPORTED,
2354 _("Filesystem does not support symbolic links"));
2355 else
2356 g_set_io_error (error,
2357 _("Error making symbolic link %s: %s"),
2358 file, errsv);
2359 return FALSE;
2361 return TRUE;
2362 #else
2363 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("Symbolic links not supported"));
2364 return FALSE;
2365 #endif
2369 static gboolean
2370 g_local_file_copy (GFile *source,
2371 GFile *destination,
2372 GFileCopyFlags flags,
2373 GCancellable *cancellable,
2374 GFileProgressCallback progress_callback,
2375 gpointer progress_callback_data,
2376 GError **error)
2378 /* Fall back to default copy */
2379 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2380 return FALSE;
2383 static gboolean
2384 g_local_file_move (GFile *source,
2385 GFile *destination,
2386 GFileCopyFlags flags,
2387 GCancellable *cancellable,
2388 GFileProgressCallback progress_callback,
2389 gpointer progress_callback_data,
2390 GError **error)
2392 GLocalFile *local_source, *local_destination;
2393 GStatBuf statbuf;
2394 gboolean destination_exist, source_is_dir;
2395 char *backup_name;
2396 int res;
2397 off_t source_size;
2398 GVfsClass *class;
2399 GVfs *vfs;
2401 if (!G_IS_LOCAL_FILE (source) ||
2402 !G_IS_LOCAL_FILE (destination))
2404 /* Fall back to default move */
2405 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2406 return FALSE;
2409 local_source = G_LOCAL_FILE (source);
2410 local_destination = G_LOCAL_FILE (destination);
2412 res = g_lstat (local_source->filename, &statbuf);
2413 if (res == -1)
2415 int errsv = errno;
2417 g_set_io_error (error,
2418 _("Error moving file %s: %s"),
2419 source, errsv);
2420 return FALSE;
2423 source_is_dir = S_ISDIR (statbuf.st_mode);
2424 source_size = statbuf.st_size;
2426 destination_exist = FALSE;
2427 res = g_lstat (local_destination->filename, &statbuf);
2428 if (res == 0)
2430 destination_exist = TRUE; /* Target file exists */
2432 if (flags & G_FILE_COPY_OVERWRITE)
2434 /* Always fail on dirs, even with overwrite */
2435 if (S_ISDIR (statbuf.st_mode))
2437 if (source_is_dir)
2438 g_set_error_literal (error,
2439 G_IO_ERROR,
2440 G_IO_ERROR_WOULD_MERGE,
2441 _("Can’t move directory over directory"));
2442 else
2443 g_set_error_literal (error,
2444 G_IO_ERROR,
2445 G_IO_ERROR_IS_DIRECTORY,
2446 _("Can’t copy over directory"));
2447 return FALSE;
2450 else
2452 g_set_io_error (error,
2453 _("Error moving file %s: %s"),
2454 source, EEXIST);
2455 return FALSE;
2459 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2461 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2462 if (g_rename (local_destination->filename, backup_name) == -1)
2464 g_set_error_literal (error,
2465 G_IO_ERROR,
2466 G_IO_ERROR_CANT_CREATE_BACKUP,
2467 _("Backup file creation failed"));
2468 g_free (backup_name);
2469 return FALSE;
2471 g_free (backup_name);
2472 destination_exist = FALSE; /* It did, but no more */
2475 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2477 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2478 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2479 res = g_unlink (local_destination->filename);
2480 if (res == -1)
2482 int errsv = errno;
2484 g_set_error (error, G_IO_ERROR,
2485 g_io_error_from_errno (errsv),
2486 _("Error removing target file: %s"),
2487 g_strerror (errsv));
2488 return FALSE;
2492 if (g_rename (local_source->filename, local_destination->filename) == -1)
2494 int errsv = errno;
2496 if (errsv == EXDEV)
2497 /* This will cause the fallback code to run */
2498 g_set_error_literal (error, G_IO_ERROR,
2499 G_IO_ERROR_NOT_SUPPORTED,
2500 _("Move between mounts not supported"));
2501 else if (errsv == EINVAL)
2502 /* This must be an invalid filename, on e.g. FAT, or
2503 we're trying to move the file into itself...
2504 We return invalid filename for both... */
2505 g_set_error_literal (error, G_IO_ERROR,
2506 G_IO_ERROR_INVALID_FILENAME,
2507 _("Invalid filename"));
2508 else
2509 g_set_io_error (error,
2510 _("Error moving file %s: %s"),
2511 source, errsv);
2512 return FALSE;
2515 vfs = g_vfs_get_default ();
2516 class = G_VFS_GET_CLASS (vfs);
2517 if (class->local_file_moved)
2518 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2520 /* Make sure we send full copied size */
2521 if (progress_callback)
2522 progress_callback (source_size, source_size, progress_callback_data);
2524 return TRUE;
2527 #ifdef G_OS_WIN32
2529 gboolean
2530 g_local_file_is_remote (const gchar *filename)
2532 return FALSE;
2535 #else
2537 static gboolean
2538 is_remote_fs (const gchar *filename)
2540 const char *fsname = NULL;
2542 #ifdef USE_STATFS
2543 struct statfs statfs_buffer;
2544 int statfs_result = 0;
2546 #if STATFS_ARGS == 2
2547 statfs_result = statfs (filename, &statfs_buffer);
2548 #elif STATFS_ARGS == 4
2549 statfs_result = statfs (filename, &statfs_buffer, sizeof (statfs_buffer), 0);
2550 #endif
2552 #elif defined(USE_STATVFS)
2553 struct statvfs statfs_buffer;
2554 int statfs_result = 0;
2556 statfs_result = statvfs (filename, &statfs_buffer);
2557 #else
2558 return FALSE;
2559 #endif
2561 if (statfs_result == -1)
2562 return FALSE;
2564 #ifdef USE_STATFS
2565 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
2566 fsname = statfs_buffer.f_fstypename;
2567 #else
2568 fsname = get_fs_type (statfs_buffer.f_type);
2569 #endif
2571 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
2572 fsname = statfs_buffer.f_basetype;
2573 #endif
2575 if (fsname != NULL)
2577 if (strcmp (fsname, "nfs") == 0)
2578 return TRUE;
2579 if (strcmp (fsname, "nfs4") == 0)
2580 return TRUE;
2583 return FALSE;
2586 gboolean
2587 g_local_file_is_remote (const gchar *filename)
2589 static gboolean remote_home;
2590 static gsize initialized;
2591 const gchar *home;
2593 home = g_get_home_dir ();
2594 if (path_has_prefix (filename, home))
2596 if (g_once_init_enter (&initialized))
2598 remote_home = is_remote_fs (home);
2599 g_once_init_leave (&initialized, TRUE);
2601 return remote_home;
2604 return FALSE;
2606 #endif /* !G_OS_WIN32 */
2608 static GFileMonitor*
2609 g_local_file_monitor_dir (GFile *file,
2610 GFileMonitorFlags flags,
2611 GCancellable *cancellable,
2612 GError **error)
2614 GLocalFile *local_file = G_LOCAL_FILE (file);
2616 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2619 static GFileMonitor*
2620 g_local_file_monitor_file (GFile *file,
2621 GFileMonitorFlags flags,
2622 GCancellable *cancellable,
2623 GError **error)
2625 GLocalFile *local_file = G_LOCAL_FILE (file);
2627 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2630 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2632 * If available, we use fopenat() in preference to filenames for
2633 * efficiency and safety reasons. We know that fopenat() is available
2634 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2635 * defined as a macro.
2637 * We use a linked list of stack-allocated GSList nodes in order to be
2638 * able to reconstruct the filename for error messages. We actually
2639 * pass the filename to operate on through the top node of the list.
2641 * In case we're using openat(), this top filename will be a basename
2642 * which should be opened in the directory which has also had its fd
2643 * passed along. If we're not using openat() then it will be a full
2644 * absolute filename.
2647 static gboolean
2648 g_local_file_measure_size_error (GFileMeasureFlags flags,
2649 gint saved_errno,
2650 GSList *name,
2651 GError **error)
2653 /* Only report an error if we were at the toplevel or if the caller
2654 * requested reporting of all errors.
2656 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2658 GString *filename;
2659 GSList *node;
2661 /* Skip some work if there is no error return */
2662 if (!error)
2663 return FALSE;
2665 #ifdef AT_FDCWD
2666 /* If using openat() we need to rebuild the filename for the message */
2667 filename = g_string_new (name->data);
2668 for (node = name->next; node; node = node->next)
2670 gchar *utf8;
2672 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2673 utf8 = g_filename_display_name (node->data);
2674 g_string_prepend (filename, utf8);
2675 g_free (utf8);
2677 #else
2679 gchar *utf8;
2681 /* Otherwise, we already have it, so just use it. */
2682 node = name;
2683 filename = g_string_new (NULL);
2684 utf8 = g_filename_display_name (node->data);
2685 g_string_append (filename, utf8);
2686 g_free (utf8);
2688 #endif
2690 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2691 _("Could not determine the disk usage of %s: %s"),
2692 filename->str, g_strerror (saved_errno));
2694 g_string_free (filename, TRUE);
2696 return FALSE;
2699 else
2700 /* We're not reporting this error... */
2701 return TRUE;
2704 typedef struct
2706 GFileMeasureFlags flags;
2707 dev_t contained_on;
2708 GCancellable *cancellable;
2710 GFileMeasureProgressCallback progress_callback;
2711 gpointer progress_data;
2713 guint64 disk_usage;
2714 guint64 num_dirs;
2715 guint64 num_files;
2717 guint64 last_progress_report;
2718 } MeasureState;
2720 static gboolean
2721 g_local_file_measure_size_of_contents (gint fd,
2722 GSList *dir_name,
2723 MeasureState *state,
2724 GError **error);
2726 static gboolean
2727 g_local_file_measure_size_of_file (gint parent_fd,
2728 GSList *name,
2729 MeasureState *state,
2730 GError **error)
2732 GLocalFileStat buf;
2734 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2735 return FALSE;
2737 #if defined (AT_FDCWD)
2738 if (fstatat (parent_fd, name->data, &buf, AT_SYMLINK_NOFOLLOW) != 0)
2740 int errsv = errno;
2741 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2743 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2744 if (g_lstat (name->data, &buf) != 0)
2746 int errsv = errno;
2747 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2749 #else /* !AT_FDCWD && !HAVE_LSTAT && G_OS_WIN32 */
2750 if (GLIB_PRIVATE_CALL (g_win32_lstat_utf8) (name->data, &buf) != 0)
2752 int errsv = errno;
2753 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2755 #endif
2757 if (name->next)
2759 /* If not at the toplevel, check for a device boundary. */
2761 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2762 if (state->contained_on != buf.st_dev)
2763 return TRUE;
2765 else
2767 /* If, however, this is the toplevel, set the device number so
2768 * that recursive invocations can compare against it.
2770 state->contained_on = buf.st_dev;
2773 #if defined (G_OS_WIN32)
2774 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2775 state->disk_usage += buf.allocated_size;
2776 else
2777 #elif defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2778 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2779 state->disk_usage += buf.st_blocks * G_GUINT64_CONSTANT (512);
2780 else
2781 #endif
2782 state->disk_usage += buf.st_size;
2784 if (S_ISDIR (buf.st_mode))
2785 state->num_dirs++;
2786 else
2787 state->num_files++;
2789 if (state->progress_callback)
2791 /* We could attempt to do some cleverness here in order to avoid
2792 * calling clock_gettime() so much, but we're doing stats and opens
2793 * all over the place already...
2795 if (state->last_progress_report)
2797 guint64 now;
2799 now = g_get_monotonic_time ();
2801 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2803 (* state->progress_callback) (TRUE,
2804 state->disk_usage, state->num_dirs, state->num_files,
2805 state->progress_data);
2806 state->last_progress_report = now;
2809 else
2811 /* We must do an initial report to inform that more reports
2812 * will be coming.
2814 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2815 state->last_progress_report = g_get_monotonic_time ();
2819 if (S_ISDIR (buf.st_mode))
2821 int dir_fd = -1;
2822 int errsv;
2824 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2825 return FALSE;
2827 #ifdef AT_FDCWD
2828 #ifdef HAVE_OPEN_O_DIRECTORY
2829 dir_fd = openat (parent_fd, name->data, O_RDONLY|O_DIRECTORY);
2830 #else
2831 dir_fd = openat (parent_fd, name->data, O_RDONLY);
2832 #endif
2833 errsv = errno;
2834 if (dir_fd < 0)
2835 return g_local_file_measure_size_error (state->flags, errsv, name, error);
2836 #endif
2838 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2839 return FALSE;
2842 return TRUE;
2845 static gboolean
2846 g_local_file_measure_size_of_contents (gint fd,
2847 GSList *dir_name,
2848 MeasureState *state,
2849 GError **error)
2851 gboolean success = TRUE;
2852 const gchar *name;
2853 GDir *dir;
2855 #ifdef AT_FDCWD
2857 /* If this fails, we want to preserve the errno from fopendir() */
2858 DIR *dirp;
2859 dirp = fdopendir (fd);
2860 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2862 #else
2863 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2864 #endif
2866 if (dir == NULL)
2868 gint saved_errno = errno;
2870 #ifdef AT_FDCWD
2871 close (fd);
2872 #endif
2874 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2877 while (success && (name = g_dir_read_name (dir)))
2879 GSList node;
2881 node.next = dir_name;
2882 #ifdef AT_FDCWD
2883 node.data = (gchar *) name;
2884 #else
2885 node.data = g_build_filename (dir_name->data, name, NULL);
2886 #endif
2888 success = g_local_file_measure_size_of_file (fd, &node, state, error);
2890 #ifndef AT_FDCWD
2891 g_free (node.data);
2892 #endif
2895 g_dir_close (dir);
2897 return success;
2900 static gboolean
2901 g_local_file_measure_disk_usage (GFile *file,
2902 GFileMeasureFlags flags,
2903 GCancellable *cancellable,
2904 GFileMeasureProgressCallback progress_callback,
2905 gpointer progress_data,
2906 guint64 *disk_usage,
2907 guint64 *num_dirs,
2908 guint64 *num_files,
2909 GError **error)
2911 GLocalFile *local_file = G_LOCAL_FILE (file);
2912 MeasureState state = { 0, };
2913 gint root_fd = -1;
2914 GSList node;
2916 state.flags = flags;
2917 state.cancellable = cancellable;
2918 state.progress_callback = progress_callback;
2919 state.progress_data = progress_data;
2921 #ifdef AT_FDCWD
2922 root_fd = AT_FDCWD;
2923 #endif
2925 node.data = local_file->filename;
2926 node.next = NULL;
2928 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
2929 return FALSE;
2931 if (disk_usage)
2932 *disk_usage = state.disk_usage;
2934 if (num_dirs)
2935 *num_dirs = state.num_dirs;
2937 if (num_files)
2938 *num_files = state.num_files;
2940 return TRUE;
2943 static void
2944 g_local_file_file_iface_init (GFileIface *iface)
2946 iface->dup = g_local_file_dup;
2947 iface->hash = g_local_file_hash;
2948 iface->equal = g_local_file_equal;
2949 iface->is_native = g_local_file_is_native;
2950 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2951 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2952 iface->get_basename = g_local_file_get_basename;
2953 iface->get_path = g_local_file_get_path;
2954 iface->get_uri = g_local_file_get_uri;
2955 iface->get_parse_name = g_local_file_get_parse_name;
2956 iface->get_parent = g_local_file_get_parent;
2957 iface->prefix_matches = g_local_file_prefix_matches;
2958 iface->get_relative_path = g_local_file_get_relative_path;
2959 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2960 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2961 iface->set_display_name = g_local_file_set_display_name;
2962 iface->enumerate_children = g_local_file_enumerate_children;
2963 iface->query_info = g_local_file_query_info;
2964 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2965 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2966 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2967 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2968 iface->set_attribute = g_local_file_set_attribute;
2969 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2970 iface->read_fn = g_local_file_read;
2971 iface->append_to = g_local_file_append_to;
2972 iface->create = g_local_file_create;
2973 iface->replace = g_local_file_replace;
2974 iface->open_readwrite = g_local_file_open_readwrite;
2975 iface->create_readwrite = g_local_file_create_readwrite;
2976 iface->replace_readwrite = g_local_file_replace_readwrite;
2977 iface->delete_file = g_local_file_delete;
2978 iface->trash = g_local_file_trash;
2979 iface->make_directory = g_local_file_make_directory;
2980 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2981 iface->copy = g_local_file_copy;
2982 iface->move = g_local_file_move;
2983 iface->monitor_dir = g_local_file_monitor_dir;
2984 iface->monitor_file = g_local_file_monitor_file;
2985 iface->measure_disk_usage = g_local_file_measure_disk_usage;
2987 iface->supports_thread_contexts = TRUE;