Updated Italian translation
[glib.git] / gio / glocalfile.c
bloba5a6beb45055c93b8e74cd1f37602f717da812cb
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 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 "glocalfileinfo.h"
55 #include "glocalfileenumerator.h"
56 #include "glocalfileinputstream.h"
57 #include "glocalfileoutputstream.h"
58 #include "glocalfileiostream.h"
59 #include "glocalfilemonitor.h"
60 #include "gmountprivate.h"
61 #include "gunixmounts.h"
62 #include "gioerror.h"
63 #include <glib/gstdio.h>
64 #include "glibintl.h"
65 #ifdef G_OS_UNIX
66 #include "glib-unix.h"
67 #endif
68 #include "glib-private.h"
70 #include "glib-private.h"
72 #ifdef G_OS_WIN32
73 #include <windows.h>
74 #include <io.h>
75 #include <direct.h>
77 #ifndef FILE_READ_ONLY_VOLUME
78 #define FILE_READ_ONLY_VOLUME 0x00080000
79 #endif
81 #ifndef S_ISDIR
82 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
83 #endif
84 #ifndef S_ISLNK
85 #define S_ISLNK(m) (0)
86 #endif
87 #endif
90 static void g_local_file_file_iface_init (GFileIface *iface);
92 static GFileAttributeInfoList *local_writable_attributes = NULL;
93 static /* GFileAttributeInfoList * */ gsize local_writable_namespaces = 0;
95 struct _GLocalFile
97 GObject parent_instance;
99 char *filename;
102 #define g_local_file_get_type _g_local_file_get_type
103 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
104 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
105 g_local_file_file_iface_init))
107 static char *find_mountpoint_for (const char *file, dev_t dev);
109 static void
110 g_local_file_finalize (GObject *object)
112 GLocalFile *local;
114 local = G_LOCAL_FILE (object);
116 g_free (local->filename);
118 G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
121 static void
122 g_local_file_class_init (GLocalFileClass *klass)
124 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
125 GFileAttributeInfoList *list;
127 gobject_class->finalize = g_local_file_finalize;
129 /* Set up attribute lists */
131 /* Writable attributes: */
133 list = g_file_attribute_info_list_new ();
135 g_file_attribute_info_list_add (list,
136 G_FILE_ATTRIBUTE_UNIX_MODE,
137 G_FILE_ATTRIBUTE_TYPE_UINT32,
138 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
139 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
141 #ifdef G_OS_UNIX
142 g_file_attribute_info_list_add (list,
143 G_FILE_ATTRIBUTE_UNIX_UID,
144 G_FILE_ATTRIBUTE_TYPE_UINT32,
145 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
146 g_file_attribute_info_list_add (list,
147 G_FILE_ATTRIBUTE_UNIX_GID,
148 G_FILE_ATTRIBUTE_TYPE_UINT32,
149 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
150 #endif
152 #ifdef HAVE_SYMLINK
153 g_file_attribute_info_list_add (list,
154 G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
155 G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
157 #endif
159 #ifdef HAVE_UTIMES
160 g_file_attribute_info_list_add (list,
161 G_FILE_ATTRIBUTE_TIME_MODIFIED,
162 G_FILE_ATTRIBUTE_TYPE_UINT64,
163 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
164 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
165 g_file_attribute_info_list_add (list,
166 G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
167 G_FILE_ATTRIBUTE_TYPE_UINT32,
168 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
169 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
170 /* When copying, the target file is accessed. Replicating
171 * the source access time does not make sense in this case.
173 g_file_attribute_info_list_add (list,
174 G_FILE_ATTRIBUTE_TIME_ACCESS,
175 G_FILE_ATTRIBUTE_TYPE_UINT64,
176 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
177 g_file_attribute_info_list_add (list,
178 G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
179 G_FILE_ATTRIBUTE_TYPE_UINT32,
180 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
181 #endif
183 local_writable_attributes = list;
186 static void
187 g_local_file_init (GLocalFile *local)
191 const char *
192 _g_local_file_get_filename (GLocalFile *file)
194 return file->filename;
197 static char *
198 canonicalize_filename (const char *filename)
200 char *canon, *start, *p, *q;
201 char *cwd;
202 int i;
204 if (!g_path_is_absolute (filename))
206 cwd = g_get_current_dir ();
207 canon = g_build_filename (cwd, filename, NULL);
208 g_free (cwd);
210 else
211 canon = g_strdup (filename);
213 start = (char *)g_path_skip_root (canon);
215 if (start == NULL)
217 /* This shouldn't really happen, as g_get_current_dir() should
218 return an absolute pathname, but bug 573843 shows this is
219 not always happening */
220 g_free (canon);
221 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
224 /* POSIX allows double slashes at the start to
225 * mean something special (as does windows too).
226 * So, "//" != "/", but more than two slashes
227 * is treated as "/".
229 i = 0;
230 for (p = start - 1;
231 (p >= canon) &&
232 G_IS_DIR_SEPARATOR (*p);
233 p--)
234 i++;
235 if (i > 2)
237 i -= 1;
238 start -= i;
239 memmove (start, start+i, strlen (start+i)+1);
242 /* Make sure we're using the canonical dir separator */
243 p++;
244 while (p < start && G_IS_DIR_SEPARATOR (*p))
245 *p++ = G_DIR_SEPARATOR;
247 p = start;
248 while (*p != 0)
250 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
252 memmove (p, p+1, strlen (p+1)+1);
254 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
256 q = p + 2;
257 /* Skip previous separator */
258 p = p - 2;
259 if (p < start)
260 p = start;
261 while (p > start && !G_IS_DIR_SEPARATOR (*p))
262 p--;
263 if (G_IS_DIR_SEPARATOR (*p))
264 *p++ = G_DIR_SEPARATOR;
265 memmove (p, q, strlen (q)+1);
267 else
269 /* Skip until next separator */
270 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
271 p++;
273 if (*p != 0)
275 /* Canonicalize one separator */
276 *p++ = G_DIR_SEPARATOR;
280 /* Remove additional separators */
281 q = p;
282 while (*q && G_IS_DIR_SEPARATOR (*q))
283 q++;
285 if (p != q)
286 memmove (p, q, strlen (q)+1);
289 /* Remove trailing slashes */
290 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
291 *(p-1) = 0;
293 return canon;
296 GFile *
297 _g_local_file_new (const char *filename)
299 GLocalFile *local;
301 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
302 local->filename = canonicalize_filename (filename);
304 return G_FILE (local);
307 /*< internal >
308 * g_local_file_new_from_dirname_and_basename:
309 * @dirname: an absolute, canonical directory name
310 * @basename: the name of a child inside @dirname
312 * Creates a #GFile from @dirname and @basename.
314 * This is more efficient than pasting the fields together for yourself
315 * and creating a #GFile from the result, and also more efficient than
316 * creating a #GFile for the dirname and using g_file_get_child().
318 * @dirname must be canonical, as per GLocalFile's opinion of what
319 * canonical means. This means that you should only pass strings that
320 * were returned by _g_local_file_get_filename().
322 * Returns: a #GFile
324 GFile *
325 g_local_file_new_from_dirname_and_basename (const gchar *dirname,
326 const gchar *basename)
328 GLocalFile *local;
330 g_return_val_if_fail (dirname != NULL, NULL);
331 g_return_val_if_fail (basename && basename[0] && !strchr (basename, '/'), NULL);
333 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
334 local->filename = g_build_filename (dirname, basename, NULL);
336 return G_FILE (local);
339 static gboolean
340 g_local_file_is_native (GFile *file)
342 return TRUE;
345 static gboolean
346 g_local_file_has_uri_scheme (GFile *file,
347 const char *uri_scheme)
349 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
352 static char *
353 g_local_file_get_uri_scheme (GFile *file)
355 return g_strdup ("file");
358 static char *
359 g_local_file_get_basename (GFile *file)
361 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
364 static char *
365 g_local_file_get_path (GFile *file)
367 return g_strdup (G_LOCAL_FILE (file)->filename);
370 static char *
371 g_local_file_get_uri (GFile *file)
373 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
376 static gboolean
377 get_filename_charset (const gchar **filename_charset)
379 const gchar **charsets;
380 gboolean is_utf8;
382 is_utf8 = g_get_filename_charsets (&charsets);
384 if (filename_charset)
385 *filename_charset = charsets[0];
387 return is_utf8;
390 static gboolean
391 name_is_valid_for_display (const char *string,
392 gboolean is_valid_utf8)
394 char c;
396 if (!is_valid_utf8 &&
397 !g_utf8_validate (string, -1, NULL))
398 return FALSE;
400 while ((c = *string++) != 0)
402 if (g_ascii_iscntrl (c))
403 return FALSE;
406 return TRUE;
409 static char *
410 g_local_file_get_parse_name (GFile *file)
412 const char *filename;
413 char *parse_name;
414 const gchar *charset;
415 char *utf8_filename;
416 char *roundtripped_filename;
417 gboolean free_utf8_filename;
418 gboolean is_valid_utf8;
419 char *escaped_path;
421 filename = G_LOCAL_FILE (file)->filename;
422 if (get_filename_charset (&charset))
424 utf8_filename = (char *)filename;
425 free_utf8_filename = FALSE;
426 is_valid_utf8 = FALSE; /* Can't guarantee this */
428 else
430 utf8_filename = g_convert (filename, -1,
431 "UTF-8", charset, NULL, NULL, NULL);
432 free_utf8_filename = TRUE;
433 is_valid_utf8 = TRUE;
435 if (utf8_filename != NULL)
437 /* Make sure we can roundtrip: */
438 roundtripped_filename = g_convert (utf8_filename, -1,
439 charset, "UTF-8", NULL, NULL, NULL);
441 if (roundtripped_filename == NULL ||
442 strcmp (filename, roundtripped_filename) != 0)
444 g_free (utf8_filename);
445 utf8_filename = NULL;
448 g_free (roundtripped_filename);
452 if (utf8_filename != NULL &&
453 name_is_valid_for_display (utf8_filename, is_valid_utf8))
455 if (free_utf8_filename)
456 parse_name = utf8_filename;
457 else
458 parse_name = g_strdup (utf8_filename);
460 else
462 #ifdef G_OS_WIN32
463 char *dup_filename, *p, *backslash;
465 /* Turn backslashes into forward slashes like
466 * g_filename_to_uri() would do (but we can't use that because
467 * it doesn't output IRIs).
469 dup_filename = g_strdup (filename);
470 filename = p = dup_filename;
472 while ((backslash = strchr (p, '\\')) != NULL)
474 *backslash = '/';
475 p = backslash + 1;
477 #endif
479 escaped_path = g_uri_escape_string (filename,
480 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
481 TRUE);
482 parse_name = g_strconcat ("file://",
483 (*escaped_path != '/') ? "/" : "",
484 escaped_path,
485 NULL);
487 g_free (escaped_path);
488 #ifdef G_OS_WIN32
489 g_free (dup_filename);
490 #endif
491 if (free_utf8_filename)
492 g_free (utf8_filename);
495 return parse_name;
498 static GFile *
499 g_local_file_get_parent (GFile *file)
501 GLocalFile *local = G_LOCAL_FILE (file);
502 const char *non_root;
503 char *dirname;
504 GFile *parent;
506 /* Check for root */
507 non_root = g_path_skip_root (local->filename);
508 if (*non_root == 0)
509 return NULL;
511 dirname = g_path_get_dirname (local->filename);
512 parent = _g_local_file_new (dirname);
513 g_free (dirname);
514 return parent;
517 static GFile *
518 g_local_file_dup (GFile *file)
520 GLocalFile *local = G_LOCAL_FILE (file);
522 return _g_local_file_new (local->filename);
525 static guint
526 g_local_file_hash (GFile *file)
528 GLocalFile *local = G_LOCAL_FILE (file);
530 return g_str_hash (local->filename);
533 static gboolean
534 g_local_file_equal (GFile *file1,
535 GFile *file2)
537 GLocalFile *local1 = G_LOCAL_FILE (file1);
538 GLocalFile *local2 = G_LOCAL_FILE (file2);
540 return g_str_equal (local1->filename, local2->filename);
543 static const char *
544 match_prefix (const char *path,
545 const char *prefix)
547 int prefix_len;
549 prefix_len = strlen (prefix);
550 if (strncmp (path, prefix, prefix_len) != 0)
551 return NULL;
553 /* Handle the case where prefix is the root, so that
554 * the IS_DIR_SEPRARATOR check below works */
555 if (prefix_len > 0 &&
556 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
557 prefix_len--;
559 return path + prefix_len;
562 static gboolean
563 g_local_file_prefix_matches (GFile *parent,
564 GFile *descendant)
566 GLocalFile *parent_local = G_LOCAL_FILE (parent);
567 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
568 const char *remainder;
570 remainder = match_prefix (descendant_local->filename, parent_local->filename);
571 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
572 return TRUE;
573 return FALSE;
576 static char *
577 g_local_file_get_relative_path (GFile *parent,
578 GFile *descendant)
580 GLocalFile *parent_local = G_LOCAL_FILE (parent);
581 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
582 const char *remainder;
584 remainder = match_prefix (descendant_local->filename, parent_local->filename);
586 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
587 return g_strdup (remainder + 1);
588 return NULL;
591 static GFile *
592 g_local_file_resolve_relative_path (GFile *file,
593 const char *relative_path)
595 GLocalFile *local = G_LOCAL_FILE (file);
596 char *filename;
597 GFile *child;
599 if (g_path_is_absolute (relative_path))
600 return _g_local_file_new (relative_path);
602 filename = g_build_filename (local->filename, relative_path, NULL);
603 child = _g_local_file_new (filename);
604 g_free (filename);
606 return child;
609 static GFileEnumerator *
610 g_local_file_enumerate_children (GFile *file,
611 const char *attributes,
612 GFileQueryInfoFlags flags,
613 GCancellable *cancellable,
614 GError **error)
616 GLocalFile *local = G_LOCAL_FILE (file);
617 return _g_local_file_enumerator_new (local,
618 attributes, flags,
619 cancellable, error);
622 static GFile *
623 g_local_file_get_child_for_display_name (GFile *file,
624 const char *display_name,
625 GError **error)
627 GFile *new_file;
628 char *basename;
630 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
631 if (basename == NULL)
633 g_set_error (error, G_IO_ERROR,
634 G_IO_ERROR_INVALID_FILENAME,
635 _("Invalid filename %s"), display_name);
636 return NULL;
639 new_file = g_file_get_child (file, basename);
640 g_free (basename);
642 return new_file;
645 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
646 static const char *
647 get_fs_type (long f_type)
649 /* filesystem ids taken from linux manpage */
650 switch (f_type)
652 case 0xadf5:
653 return "adfs";
654 case 0x5346414f:
655 return "afs";
656 case 0x0187:
657 return "autofs";
658 case 0xADFF:
659 return "affs";
660 case 0x42465331:
661 return "befs";
662 case 0x1BADFACE:
663 return "bfs";
664 case 0x9123683E:
665 return "btrfs";
666 case 0xFF534D42:
667 return "cifs";
668 case 0x73757245:
669 return "coda";
670 case 0x012FF7B7:
671 return "coh";
672 case 0x28cd3d45:
673 return "cramfs";
674 case 0x1373:
675 return "devfs";
676 case 0x00414A53:
677 return "efs";
678 case 0x137D:
679 return "ext";
680 case 0xEF51:
681 return "ext2";
682 case 0xEF53:
683 return "ext3/ext4";
684 case 0x4244:
685 return "hfs";
686 case 0xF995E849:
687 return "hpfs";
688 case 0x958458f6:
689 return "hugetlbfs";
690 case 0x9660:
691 return "isofs";
692 case 0x72b6:
693 return "jffs2";
694 case 0x3153464a:
695 return "jfs";
696 case 0x137F:
697 return "minix";
698 case 0x138F:
699 return "minix2";
700 case 0x2468:
701 return "minix2";
702 case 0x2478:
703 return "minix22";
704 case 0x4d44:
705 return "msdos";
706 case 0x564c:
707 return "ncp";
708 case 0x6969:
709 return "nfs";
710 case 0x5346544e:
711 return "ntfs";
712 case 0x9fa1:
713 return "openprom";
714 case 0x9fa0:
715 return "proc";
716 case 0x002f:
717 return "qnx4";
718 case 0x52654973:
719 return "reiserfs";
720 case 0x7275:
721 return "romfs";
722 case 0x517B:
723 return "smb";
724 case 0x73717368:
725 return "squashfs";
726 case 0x012FF7B6:
727 return "sysv2";
728 case 0x012FF7B5:
729 return "sysv4";
730 case 0x01021994:
731 return "tmpfs";
732 case 0x15013346:
733 return "udf";
734 case 0x00011954:
735 return "ufs";
736 case 0x9fa2:
737 return "usbdevice";
738 case 0xa501FCF5:
739 return "vxfs";
740 case 0x012FF7B4:
741 return "xenix";
742 case 0x58465342:
743 return "xfs";
744 case 0x012FD16D:
745 return "xiafs";
746 case 0x52345362:
747 return "reiser4";
748 default:
749 return NULL;
752 #endif
754 #ifndef G_OS_WIN32
756 G_LOCK_DEFINE_STATIC(mount_info_hash);
757 static GHashTable *mount_info_hash = NULL;
758 static guint64 mount_info_hash_cache_time = 0;
760 typedef enum {
761 MOUNT_INFO_READONLY = 1<<0
762 } MountInfo;
764 static gboolean
765 device_equal (gconstpointer v1,
766 gconstpointer v2)
768 return *(dev_t *)v1 == *(dev_t *)v2;
771 static guint
772 device_hash (gconstpointer v)
774 return (guint) *(dev_t *)v;
777 static void
778 get_mount_info (GFileInfo *fs_info,
779 const char *path,
780 GFileAttributeMatcher *matcher)
782 GStatBuf buf;
783 gboolean got_info;
784 gpointer info_as_ptr;
785 guint mount_info;
786 char *mountpoint;
787 dev_t *dev;
788 GUnixMountEntry *mount;
789 guint64 cache_time;
791 if (g_lstat (path, &buf) != 0)
792 return;
794 G_LOCK (mount_info_hash);
796 if (mount_info_hash == NULL)
797 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
798 g_free, NULL);
801 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
802 g_hash_table_remove_all (mount_info_hash);
804 got_info = g_hash_table_lookup_extended (mount_info_hash,
805 &buf.st_dev,
806 NULL,
807 &info_as_ptr);
809 G_UNLOCK (mount_info_hash);
811 mount_info = GPOINTER_TO_UINT (info_as_ptr);
813 if (!got_info)
815 mount_info = 0;
817 mountpoint = find_mountpoint_for (path, buf.st_dev);
818 if (mountpoint == NULL)
819 mountpoint = g_strdup ("/");
821 mount = g_unix_mount_at (mountpoint, &cache_time);
822 if (mount)
824 if (g_unix_mount_is_readonly (mount))
825 mount_info |= MOUNT_INFO_READONLY;
827 g_unix_mount_free (mount);
830 g_free (mountpoint);
832 dev = g_new0 (dev_t, 1);
833 *dev = buf.st_dev;
835 G_LOCK (mount_info_hash);
836 mount_info_hash_cache_time = cache_time;
837 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
838 G_UNLOCK (mount_info_hash);
841 if (mount_info & MOUNT_INFO_READONLY)
842 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
845 #endif
847 #ifdef G_OS_WIN32
849 static gboolean
850 is_xp_or_later (void)
852 static int result = -1;
854 if (result == -1)
856 #ifndef _MSC_VER
857 OSVERSIONINFOEX ver_info = {0};
858 DWORDLONG cond_mask = 0;
859 int op = VER_GREATER_EQUAL;
861 ver_info.dwOSVersionInfoSize = sizeof ver_info;
862 ver_info.dwMajorVersion = 5;
863 ver_info.dwMinorVersion = 1;
865 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
866 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
868 result = VerifyVersionInfo (&ver_info,
869 VER_MAJORVERSION | VER_MINORVERSION,
870 cond_mask) != 0;
871 #else
872 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
873 #endif
876 return result;
879 static wchar_t *
880 get_volume_for_path (const char *path)
882 long len;
883 wchar_t *wpath;
884 wchar_t *result;
886 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
887 result = g_new (wchar_t, MAX_PATH);
889 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
891 char *msg = g_win32_error_message (GetLastError ());
892 g_critical ("GetVolumePathName failed: %s", msg);
893 g_free (msg);
894 g_free (result);
895 g_free (wpath);
896 return NULL;
899 len = wcslen (result);
900 if (len > 0 && result[len-1] != L'\\')
902 result = g_renew (wchar_t, result, len + 2);
903 result[len] = L'\\';
904 result[len + 1] = 0;
907 g_free (wpath);
908 return result;
911 static char *
912 find_mountpoint_for (const char *file, dev_t dev)
914 wchar_t *wpath;
915 char *utf8_path;
917 wpath = get_volume_for_path (file);
918 if (!wpath)
919 return NULL;
921 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
923 g_free (wpath);
924 return utf8_path;
927 static void
928 get_filesystem_readonly (GFileInfo *info,
929 const char *path)
931 wchar_t *rootdir;
933 rootdir = get_volume_for_path (path);
935 if (rootdir)
937 if (is_xp_or_later ())
939 DWORD flags;
940 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
941 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
942 (flags & FILE_READ_ONLY_VOLUME) != 0);
944 else
946 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
947 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
951 g_free (rootdir);
954 #endif /* G_OS_WIN32 */
956 static GFileInfo *
957 g_local_file_query_filesystem_info (GFile *file,
958 const char *attributes,
959 GCancellable *cancellable,
960 GError **error)
962 GLocalFile *local = G_LOCAL_FILE (file);
963 GFileInfo *info;
964 int statfs_result = 0;
965 gboolean no_size;
966 #ifndef G_OS_WIN32
967 const char *fstype;
968 #ifdef USE_STATFS
969 guint64 block_size;
970 struct statfs statfs_buffer;
971 #elif defined(USE_STATVFS)
972 guint64 block_size;
973 struct statvfs statfs_buffer;
974 #endif /* USE_STATFS */
975 #endif /* G_OS_WIN32 */
976 GFileAttributeMatcher *attribute_matcher;
978 no_size = FALSE;
980 #ifdef USE_STATFS
982 #if STATFS_ARGS == 2
983 statfs_result = statfs (local->filename, &statfs_buffer);
984 #elif STATFS_ARGS == 4
985 statfs_result = statfs (local->filename, &statfs_buffer,
986 sizeof (statfs_buffer), 0);
987 #endif /* STATFS_ARGS == 2 */
988 block_size = statfs_buffer.f_bsize;
990 /* Many backends can't report free size (for instance the gvfs fuse
991 backend for backend not supporting this), and set f_bfree to 0,
992 but it can be 0 for real too. We treat the available == 0 and
993 free == 0 case as "both of these are invalid".
995 #ifndef G_OS_WIN32
996 if (statfs_result == 0 &&
997 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
998 no_size = TRUE;
999 #endif /* G_OS_WIN32 */
1001 #elif defined(USE_STATVFS)
1002 statfs_result = statvfs (local->filename, &statfs_buffer);
1003 block_size = statfs_buffer.f_frsize;
1004 #endif /* USE_STATFS */
1006 if (statfs_result == -1)
1008 int errsv = errno;
1010 g_set_error (error, G_IO_ERROR,
1011 g_io_error_from_errno (errsv),
1012 _("Error getting filesystem info: %s"),
1013 g_strerror (errsv));
1014 return NULL;
1017 info = g_file_info_new ();
1019 attribute_matcher = g_file_attribute_matcher_new (attributes);
1021 if (!no_size &&
1022 g_file_attribute_matcher_matches (attribute_matcher,
1023 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1025 #ifdef G_OS_WIN32
1026 gchar *localdir = g_path_get_dirname (local->filename);
1027 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1028 ULARGE_INTEGER li;
1030 g_free (localdir);
1031 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1032 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1033 g_free (wdirname);
1034 #else
1035 #if defined(USE_STATFS) || defined(USE_STATVFS)
1036 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1037 #endif
1038 #endif
1040 if (!no_size &&
1041 g_file_attribute_matcher_matches (attribute_matcher,
1042 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1044 #ifdef G_OS_WIN32
1045 gchar *localdir = g_path_get_dirname (local->filename);
1046 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1047 ULARGE_INTEGER li;
1049 g_free (localdir);
1050 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1051 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1052 g_free (wdirname);
1053 #else
1054 #if defined(USE_STATFS) || defined(USE_STATVFS)
1055 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1056 #endif
1057 #endif /* G_OS_WIN32 */
1060 if (!no_size &&
1061 g_file_attribute_matcher_matches (attribute_matcher,
1062 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1064 #ifdef G_OS_WIN32
1065 gchar *localdir = g_path_get_dirname (local->filename);
1066 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1067 ULARGE_INTEGER li_free;
1068 ULARGE_INTEGER li_total;
1070 g_free (localdir);
1071 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1072 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1073 g_free (wdirname);
1074 #else
1075 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1076 #endif /* G_OS_WIN32 */
1079 #ifndef G_OS_WIN32
1080 #ifdef USE_STATFS
1081 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1082 fstype = g_strdup (statfs_buffer.f_fstypename);
1083 #else
1084 fstype = get_fs_type (statfs_buffer.f_type);
1085 #endif
1087 #elif defined(USE_STATVFS)
1088 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1089 fstype = g_strdup (statfs_buffer.f_fstypename);
1090 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1091 fstype = g_strdup (statfs_buffer.f_basetype);
1092 #else
1093 fstype = NULL;
1094 #endif
1095 #endif /* USE_STATFS */
1097 if (fstype &&
1098 g_file_attribute_matcher_matches (attribute_matcher,
1099 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1100 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1101 #endif /* G_OS_WIN32 */
1103 if (g_file_attribute_matcher_matches (attribute_matcher,
1104 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1106 #ifdef G_OS_WIN32
1107 get_filesystem_readonly (info, local->filename);
1108 #else
1109 get_mount_info (info, local->filename, attribute_matcher);
1110 #endif /* G_OS_WIN32 */
1113 g_file_attribute_matcher_unref (attribute_matcher);
1115 return info;
1118 static GMount *
1119 g_local_file_find_enclosing_mount (GFile *file,
1120 GCancellable *cancellable,
1121 GError **error)
1123 GLocalFile *local = G_LOCAL_FILE (file);
1124 GStatBuf buf;
1125 char *mountpoint;
1126 GMount *mount;
1128 if (g_lstat (local->filename, &buf) != 0)
1130 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1131 /* Translators: This is an error message when trying to
1132 * find the enclosing (user visible) mount of a file, but
1133 * none exists. */
1134 _("Containing mount does not exist"));
1135 return NULL;
1138 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1139 if (mountpoint == NULL)
1141 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1142 /* Translators: This is an error message when trying to
1143 * find the enclosing (user visible) mount of a file, but
1144 * none exists. */
1145 _("Containing mount does not exist"));
1146 return NULL;
1149 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1150 g_free (mountpoint);
1151 if (mount)
1152 return mount;
1154 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1155 /* Translators: This is an error message when trying to find
1156 * the enclosing (user visible) mount of a file, but none
1157 * exists. */
1158 _("Containing mount does not exist"));
1159 return NULL;
1162 static GFile *
1163 g_local_file_set_display_name (GFile *file,
1164 const char *display_name,
1165 GCancellable *cancellable,
1166 GError **error)
1168 GLocalFile *local, *new_local;
1169 GFile *new_file, *parent;
1170 GStatBuf statbuf;
1171 GVfsClass *class;
1172 GVfs *vfs;
1173 int errsv;
1175 parent = g_file_get_parent (file);
1176 if (parent == NULL)
1178 g_set_error_literal (error, G_IO_ERROR,
1179 G_IO_ERROR_FAILED,
1180 _("Can't rename root directory"));
1181 return NULL;
1184 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1185 g_object_unref (parent);
1187 if (new_file == NULL)
1188 return NULL;
1189 local = G_LOCAL_FILE (file);
1190 new_local = G_LOCAL_FILE (new_file);
1192 if (g_lstat (new_local->filename, &statbuf) == -1)
1194 errsv = errno;
1196 if (errsv != ENOENT)
1198 g_set_error (error, G_IO_ERROR,
1199 g_io_error_from_errno (errsv),
1200 _("Error renaming file: %s"),
1201 g_strerror (errsv));
1202 return NULL;
1205 else
1207 g_set_error_literal (error, G_IO_ERROR,
1208 G_IO_ERROR_EXISTS,
1209 _("Can't rename file, filename already exists"));
1210 return NULL;
1213 if (g_rename (local->filename, new_local->filename) == -1)
1215 errsv = errno;
1217 if (errsv == EINVAL)
1218 /* We can't get a rename file into itself error herer,
1219 so this must be an invalid filename, on e.g. FAT */
1220 g_set_error_literal (error, G_IO_ERROR,
1221 G_IO_ERROR_INVALID_FILENAME,
1222 _("Invalid filename"));
1223 else
1224 g_set_error (error, G_IO_ERROR,
1225 g_io_error_from_errno (errsv),
1226 _("Error renaming file: %s"),
1227 g_strerror (errsv));
1228 g_object_unref (new_file);
1229 return NULL;
1232 vfs = g_vfs_get_default ();
1233 class = G_VFS_GET_CLASS (vfs);
1234 if (class->local_file_moved)
1235 class->local_file_moved (vfs, local->filename, new_local->filename);
1237 return new_file;
1240 static GFileInfo *
1241 g_local_file_query_info (GFile *file,
1242 const char *attributes,
1243 GFileQueryInfoFlags flags,
1244 GCancellable *cancellable,
1245 GError **error)
1247 GLocalFile *local = G_LOCAL_FILE (file);
1248 GFileInfo *info;
1249 GFileAttributeMatcher *matcher;
1250 char *basename, *dirname;
1251 GLocalParentFileInfo parent_info;
1253 matcher = g_file_attribute_matcher_new (attributes);
1255 basename = g_path_get_basename (local->filename);
1257 dirname = g_path_get_dirname (local->filename);
1258 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1259 g_free (dirname);
1261 info = _g_local_file_info_get (basename, local->filename,
1262 matcher, flags, &parent_info,
1263 error);
1266 _g_local_file_info_free_parent_info (&parent_info);
1267 g_free (basename);
1269 g_file_attribute_matcher_unref (matcher);
1271 return info;
1274 static GFileAttributeInfoList *
1275 g_local_file_query_settable_attributes (GFile *file,
1276 GCancellable *cancellable,
1277 GError **error)
1279 return g_file_attribute_info_list_ref (local_writable_attributes);
1282 static GFileAttributeInfoList *
1283 g_local_file_query_writable_namespaces (GFile *file,
1284 GCancellable *cancellable,
1285 GError **error)
1287 GFileAttributeInfoList *list;
1288 GVfsClass *class;
1289 GVfs *vfs;
1291 if (g_once_init_enter (&local_writable_namespaces))
1293 /* Writable namespaces: */
1295 list = g_file_attribute_info_list_new ();
1297 #ifdef HAVE_XATTR
1298 g_file_attribute_info_list_add (list,
1299 "xattr",
1300 G_FILE_ATTRIBUTE_TYPE_STRING,
1301 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1302 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1303 g_file_attribute_info_list_add (list,
1304 "xattr-sys",
1305 G_FILE_ATTRIBUTE_TYPE_STRING,
1306 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1307 #endif
1309 vfs = g_vfs_get_default ();
1310 class = G_VFS_GET_CLASS (vfs);
1311 if (class->add_writable_namespaces)
1312 class->add_writable_namespaces (vfs, list);
1314 g_once_init_leave (&local_writable_namespaces, (gsize)list);
1316 list = (GFileAttributeInfoList *)local_writable_namespaces;
1318 return g_file_attribute_info_list_ref (list);
1321 static gboolean
1322 g_local_file_set_attribute (GFile *file,
1323 const char *attribute,
1324 GFileAttributeType type,
1325 gpointer value_p,
1326 GFileQueryInfoFlags flags,
1327 GCancellable *cancellable,
1328 GError **error)
1330 GLocalFile *local = G_LOCAL_FILE (file);
1332 return _g_local_file_info_set_attribute (local->filename,
1333 attribute,
1334 type,
1335 value_p,
1336 flags,
1337 cancellable,
1338 error);
1341 static gboolean
1342 g_local_file_set_attributes_from_info (GFile *file,
1343 GFileInfo *info,
1344 GFileQueryInfoFlags flags,
1345 GCancellable *cancellable,
1346 GError **error)
1348 GLocalFile *local = G_LOCAL_FILE (file);
1349 int res, chained_res;
1350 GFileIface *default_iface;
1352 res = _g_local_file_info_set_attributes (local->filename,
1353 info, flags,
1354 cancellable,
1355 error);
1357 if (!res)
1358 error = NULL; /* Don't write over error if further errors */
1360 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1362 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1364 return res && chained_res;
1367 static GFileInputStream *
1368 g_local_file_read (GFile *file,
1369 GCancellable *cancellable,
1370 GError **error)
1372 GLocalFile *local = G_LOCAL_FILE (file);
1373 int fd, ret;
1374 GLocalFileStat buf;
1376 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1377 if (fd == -1)
1379 int errsv = errno;
1381 #ifdef G_OS_WIN32
1382 if (errsv == EACCES)
1384 ret = _stati64 (local->filename, &buf);
1385 if (ret == 0 && S_ISDIR (buf.st_mode))
1387 g_set_error_literal (error, G_IO_ERROR,
1388 G_IO_ERROR_IS_DIRECTORY,
1389 _("Can't open directory"));
1390 return NULL;
1393 #endif
1395 g_set_error (error, G_IO_ERROR,
1396 g_io_error_from_errno (errsv),
1397 _("Error opening file: %s"),
1398 g_strerror (errsv));
1399 return NULL;
1402 #ifdef G_OS_WIN32
1403 ret = _fstati64 (fd, &buf);
1404 #else
1405 ret = fstat (fd, &buf);
1406 #endif
1408 if (ret == 0 && S_ISDIR (buf.st_mode))
1410 (void) g_close (fd, NULL);
1411 g_set_error_literal (error, G_IO_ERROR,
1412 G_IO_ERROR_IS_DIRECTORY,
1413 _("Can't open directory"));
1414 return NULL;
1417 return _g_local_file_input_stream_new (fd);
1420 static GFileOutputStream *
1421 g_local_file_append_to (GFile *file,
1422 GFileCreateFlags flags,
1423 GCancellable *cancellable,
1424 GError **error)
1426 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1427 flags, cancellable, error);
1430 static GFileOutputStream *
1431 g_local_file_create (GFile *file,
1432 GFileCreateFlags flags,
1433 GCancellable *cancellable,
1434 GError **error)
1436 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1437 FALSE, flags, NULL,
1438 cancellable, error);
1441 static GFileOutputStream *
1442 g_local_file_replace (GFile *file,
1443 const char *etag,
1444 gboolean make_backup,
1445 GFileCreateFlags flags,
1446 GCancellable *cancellable,
1447 GError **error)
1449 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1450 FALSE,
1451 etag, make_backup, flags, NULL,
1452 cancellable, error);
1455 static GFileIOStream *
1456 g_local_file_open_readwrite (GFile *file,
1457 GCancellable *cancellable,
1458 GError **error)
1460 GFileOutputStream *output;
1461 GFileIOStream *res;
1463 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1464 TRUE,
1465 cancellable, error);
1466 if (output == NULL)
1467 return NULL;
1469 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1470 g_object_unref (output);
1471 return res;
1474 static GFileIOStream *
1475 g_local_file_create_readwrite (GFile *file,
1476 GFileCreateFlags flags,
1477 GCancellable *cancellable,
1478 GError **error)
1480 GFileOutputStream *output;
1481 GFileIOStream *res;
1483 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1484 TRUE, flags, NULL,
1485 cancellable, error);
1486 if (output == NULL)
1487 return NULL;
1489 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1490 g_object_unref (output);
1491 return res;
1494 static GFileIOStream *
1495 g_local_file_replace_readwrite (GFile *file,
1496 const char *etag,
1497 gboolean make_backup,
1498 GFileCreateFlags flags,
1499 GCancellable *cancellable,
1500 GError **error)
1502 GFileOutputStream *output;
1503 GFileIOStream *res;
1505 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1506 TRUE,
1507 etag, make_backup, flags, NULL,
1508 cancellable, error);
1509 if (output == NULL)
1510 return NULL;
1512 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1513 g_object_unref (output);
1514 return res;
1517 static gboolean
1518 g_local_file_delete (GFile *file,
1519 GCancellable *cancellable,
1520 GError **error)
1522 GLocalFile *local = G_LOCAL_FILE (file);
1523 GVfsClass *class;
1524 GVfs *vfs;
1526 if (g_remove (local->filename) == -1)
1528 int errsv = errno;
1530 /* Posix allows EEXIST too, but the more sane error
1531 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1532 expects */
1533 if (errsv == EEXIST)
1534 errsv = ENOTEMPTY;
1536 g_set_error (error, G_IO_ERROR,
1537 g_io_error_from_errno (errsv),
1538 _("Error removing file: %s"),
1539 g_strerror (errsv));
1540 return FALSE;
1543 vfs = g_vfs_get_default ();
1544 class = G_VFS_GET_CLASS (vfs);
1545 if (class->local_file_removed)
1546 class->local_file_removed (vfs, local->filename);
1548 return TRUE;
1551 #ifndef G_OS_WIN32
1553 static char *
1554 strip_trailing_slashes (const char *path)
1556 char *path_copy;
1557 int len;
1559 path_copy = g_strdup (path);
1560 len = strlen (path_copy);
1561 while (len > 1 && path_copy[len-1] == '/')
1562 path_copy[--len] = 0;
1564 return path_copy;
1567 static char *
1568 expand_symlink (const char *link)
1570 char *resolved, *canonical, *parent, *link2;
1571 char symlink_value[4096];
1572 #ifdef G_OS_WIN32
1573 #else
1574 ssize_t res;
1575 #endif
1577 #ifdef G_OS_WIN32
1578 #else
1579 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1581 if (res == -1)
1582 return g_strdup (link);
1583 symlink_value[res] = 0;
1584 #endif
1586 if (g_path_is_absolute (symlink_value))
1587 return canonicalize_filename (symlink_value);
1588 else
1590 link2 = strip_trailing_slashes (link);
1591 parent = g_path_get_dirname (link2);
1592 g_free (link2);
1594 resolved = g_build_filename (parent, symlink_value, NULL);
1595 g_free (parent);
1597 canonical = canonicalize_filename (resolved);
1599 g_free (resolved);
1601 return canonical;
1605 static char *
1606 get_parent (const char *path,
1607 dev_t *parent_dev)
1609 char *parent, *tmp;
1610 GStatBuf parent_stat;
1611 int num_recursions;
1612 char *path_copy;
1614 path_copy = strip_trailing_slashes (path);
1616 parent = g_path_get_dirname (path_copy);
1617 if (strcmp (parent, ".") == 0 ||
1618 strcmp (parent, path_copy) == 0)
1620 g_free (parent);
1621 g_free (path_copy);
1622 return NULL;
1624 g_free (path_copy);
1626 num_recursions = 0;
1627 do {
1628 if (g_lstat (parent, &parent_stat) != 0)
1630 g_free (parent);
1631 return NULL;
1634 if (S_ISLNK (parent_stat.st_mode))
1636 tmp = parent;
1637 parent = expand_symlink (parent);
1638 g_free (tmp);
1641 num_recursions++;
1642 if (num_recursions > 12)
1644 g_free (parent);
1645 return NULL;
1647 } while (S_ISLNK (parent_stat.st_mode));
1649 *parent_dev = parent_stat.st_dev;
1651 return parent;
1654 static char *
1655 expand_all_symlinks (const char *path)
1657 char *parent, *parent_expanded;
1658 char *basename, *res;
1659 dev_t parent_dev;
1661 parent = get_parent (path, &parent_dev);
1662 if (parent)
1664 parent_expanded = expand_all_symlinks (parent);
1665 g_free (parent);
1666 basename = g_path_get_basename (path);
1667 res = g_build_filename (parent_expanded, basename, NULL);
1668 g_free (basename);
1669 g_free (parent_expanded);
1671 else
1672 res = g_strdup (path);
1674 return res;
1677 static char *
1678 find_mountpoint_for (const char *file,
1679 dev_t dev)
1681 char *dir, *parent;
1682 dev_t dir_dev, parent_dev;
1684 dir = g_strdup (file);
1685 dir_dev = dev;
1687 while (1)
1689 parent = get_parent (dir, &parent_dev);
1690 if (parent == NULL)
1691 return dir;
1693 if (parent_dev != dir_dev)
1695 g_free (parent);
1696 return dir;
1699 g_free (dir);
1700 dir = parent;
1704 static char *
1705 find_topdir_for (const char *file)
1707 char *dir;
1708 char *mountpoint = NULL;
1709 dev_t dir_dev;
1711 dir = get_parent (file, &dir_dev);
1712 if (dir == NULL)
1713 return NULL;
1715 mountpoint = find_mountpoint_for (dir, dir_dev);
1716 g_free (dir);
1718 return mountpoint;
1721 static char *
1722 get_unique_filename (const char *basename,
1723 int id)
1725 const char *dot;
1727 if (id == 1)
1728 return g_strdup (basename);
1730 dot = strchr (basename, '.');
1731 if (dot)
1732 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1733 else
1734 return g_strdup_printf ("%s.%d", basename, id);
1737 static gboolean
1738 path_has_prefix (const char *path,
1739 const char *prefix)
1741 int prefix_len;
1743 if (prefix == NULL)
1744 return TRUE;
1746 prefix_len = strlen (prefix);
1748 if (strncmp (path, prefix, prefix_len) == 0 &&
1749 (prefix_len == 0 || /* empty prefix always matches */
1750 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1751 path[prefix_len] == 0 ||
1752 path[prefix_len] == '/'))
1753 return TRUE;
1755 return FALSE;
1758 static char *
1759 try_make_relative (const char *path,
1760 const char *base)
1762 char *path2, *base2;
1763 char *relative;
1765 path2 = expand_all_symlinks (path);
1766 base2 = expand_all_symlinks (base);
1768 relative = NULL;
1769 if (path_has_prefix (path2, base2))
1771 relative = path2 + strlen (base2);
1772 while (*relative == '/')
1773 relative ++;
1774 relative = g_strdup (relative);
1776 g_free (path2);
1777 g_free (base2);
1779 if (relative)
1780 return relative;
1782 /* Failed, use abs path */
1783 return g_strdup (path);
1786 gboolean
1787 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1789 static gsize home_dev_set = 0;
1790 static dev_t home_dev;
1791 char *topdir, *globaldir, *trashdir, *tmpname;
1792 uid_t uid;
1793 char uid_str[32];
1794 GStatBuf global_stat, trash_stat;
1795 gboolean res;
1797 if (g_once_init_enter (&home_dev_set))
1799 GStatBuf home_stat;
1801 g_stat (g_get_home_dir (), &home_stat);
1802 home_dev = home_stat.st_dev;
1803 g_once_init_leave (&home_dev_set, 1);
1806 /* Assume we can trash to the home */
1807 if (dir_dev == home_dev)
1808 return TRUE;
1810 topdir = find_mountpoint_for (dirname, dir_dev);
1811 if (topdir == NULL)
1812 return FALSE;
1814 globaldir = g_build_filename (topdir, ".Trash", NULL);
1815 if (g_lstat (globaldir, &global_stat) == 0 &&
1816 S_ISDIR (global_stat.st_mode) &&
1817 (global_stat.st_mode & S_ISVTX) != 0)
1819 /* got a toplevel sysadmin created dir, assume we
1820 * can trash to it (we should be able to create a dir)
1821 * This fails for the FAT case where the ownership of
1822 * that dir would be wrong though..
1824 g_free (globaldir);
1825 g_free (topdir);
1826 return TRUE;
1828 g_free (globaldir);
1830 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1831 uid = geteuid ();
1832 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1834 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1835 trashdir = g_build_filename (topdir, tmpname, NULL);
1836 g_free (tmpname);
1838 if (g_lstat (trashdir, &trash_stat) == 0)
1840 g_free (topdir);
1841 g_free (trashdir);
1842 return S_ISDIR (trash_stat.st_mode) &&
1843 trash_stat.st_uid == uid;
1845 g_free (trashdir);
1847 /* User specific trash didn't exist, can we create it? */
1848 res = g_access (topdir, W_OK) == 0;
1849 g_free (topdir);
1851 return res;
1854 #ifdef G_OS_UNIX
1855 gboolean
1856 _g_local_file_is_lost_found_dir (const char *path, dev_t path_dev)
1858 gboolean ret = FALSE;
1859 gchar *mount_dir = NULL;
1860 size_t mount_dir_len;
1861 GStatBuf statbuf;
1863 if (!g_str_has_suffix (path, "/lost+found"))
1864 goto out;
1866 mount_dir = find_mountpoint_for (path, path_dev);
1867 if (mount_dir == NULL)
1868 goto out;
1870 mount_dir_len = strlen (mount_dir);
1871 /* We special-case rootfs ('/') since it's the only case where
1872 * mount_dir ends in '/'
1874 if (mount_dir_len == 1)
1875 mount_dir_len--;
1876 if (mount_dir_len + strlen ("/lost+found") != strlen (path))
1877 goto out;
1879 if (g_lstat (path, &statbuf) != 0)
1880 goto out;
1882 if (!(S_ISDIR (statbuf.st_mode) &&
1883 statbuf.st_uid == 0 &&
1884 statbuf.st_gid == 0))
1885 goto out;
1887 ret = TRUE;
1889 out:
1890 g_free (mount_dir);
1891 return ret;
1893 #endif
1895 static gboolean
1896 g_local_file_trash (GFile *file,
1897 GCancellable *cancellable,
1898 GError **error)
1900 GLocalFile *local = G_LOCAL_FILE (file);
1901 GStatBuf file_stat, home_stat;
1902 const char *homedir;
1903 char *trashdir, *topdir, *infodir, *filesdir;
1904 char *basename, *trashname, *trashfile, *infoname, *infofile;
1905 char *original_name, *original_name_escaped;
1906 int i;
1907 char *data;
1908 gboolean is_homedir_trash;
1909 char delete_time[32];
1910 int fd;
1911 GStatBuf trash_stat, global_stat;
1912 char *dirname, *globaldir;
1913 GVfsClass *class;
1914 GVfs *vfs;
1916 if (g_lstat (local->filename, &file_stat) != 0)
1918 int errsv = errno;
1920 g_set_error (error, G_IO_ERROR,
1921 g_io_error_from_errno (errsv),
1922 _("Error trashing file: %s"),
1923 g_strerror (errsv));
1924 return FALSE;
1927 homedir = g_get_home_dir ();
1928 g_stat (homedir, &home_stat);
1930 is_homedir_trash = FALSE;
1931 trashdir = NULL;
1932 if (file_stat.st_dev == home_stat.st_dev)
1934 is_homedir_trash = TRUE;
1935 errno = 0;
1936 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1937 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1939 char *display_name;
1940 int errsv = errno;
1942 display_name = g_filename_display_name (trashdir);
1943 g_set_error (error, G_IO_ERROR,
1944 g_io_error_from_errno (errsv),
1945 _("Unable to create trash dir %s: %s"),
1946 display_name, g_strerror (errsv));
1947 g_free (display_name);
1948 g_free (trashdir);
1949 return FALSE;
1951 topdir = g_strdup (g_get_user_data_dir ());
1953 else
1955 uid_t uid;
1956 char uid_str[32];
1958 uid = geteuid ();
1959 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1961 topdir = find_topdir_for (local->filename);
1962 if (topdir == NULL)
1964 g_set_error_literal (error, G_IO_ERROR,
1965 G_IO_ERROR_NOT_SUPPORTED,
1966 _("Unable to find toplevel directory for trash"));
1967 return FALSE;
1970 /* Try looking for global trash dir $topdir/.Trash/$uid */
1971 globaldir = g_build_filename (topdir, ".Trash", NULL);
1972 if (g_lstat (globaldir, &global_stat) == 0 &&
1973 S_ISDIR (global_stat.st_mode) &&
1974 (global_stat.st_mode & S_ISVTX) != 0)
1976 trashdir = g_build_filename (globaldir, uid_str, NULL);
1978 if (g_lstat (trashdir, &trash_stat) == 0)
1980 if (!S_ISDIR (trash_stat.st_mode) ||
1981 trash_stat.st_uid != uid)
1983 /* Not a directory or not owned by user, ignore */
1984 g_free (trashdir);
1985 trashdir = NULL;
1988 else if (g_mkdir (trashdir, 0700) == -1)
1990 g_free (trashdir);
1991 trashdir = NULL;
1994 g_free (globaldir);
1996 if (trashdir == NULL)
1998 gboolean tried_create;
2000 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
2001 dirname = g_strdup_printf (".Trash-%s", uid_str);
2002 trashdir = g_build_filename (topdir, dirname, NULL);
2003 g_free (dirname);
2005 tried_create = FALSE;
2007 retry:
2008 if (g_lstat (trashdir, &trash_stat) == 0)
2010 if (!S_ISDIR (trash_stat.st_mode) ||
2011 trash_stat.st_uid != uid)
2013 /* Remove the failed directory */
2014 if (tried_create)
2015 g_remove (trashdir);
2017 /* Not a directory or not owned by user, ignore */
2018 g_free (trashdir);
2019 trashdir = NULL;
2022 else
2024 if (!tried_create &&
2025 g_mkdir (trashdir, 0700) != -1)
2027 /* Ensure that the created dir has the right uid etc.
2028 This might fail on e.g. a FAT dir */
2029 tried_create = TRUE;
2030 goto retry;
2032 else
2034 g_free (trashdir);
2035 trashdir = NULL;
2040 if (trashdir == NULL)
2042 g_free (topdir);
2043 g_set_error_literal (error, G_IO_ERROR,
2044 G_IO_ERROR_NOT_SUPPORTED,
2045 _("Unable to find or create trash directory"));
2046 return FALSE;
2050 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
2052 infodir = g_build_filename (trashdir, "info", NULL);
2053 filesdir = g_build_filename (trashdir, "files", NULL);
2054 g_free (trashdir);
2056 /* Make sure we have the subdirectories */
2057 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
2058 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
2060 g_free (topdir);
2061 g_free (infodir);
2062 g_free (filesdir);
2063 g_set_error_literal (error, G_IO_ERROR,
2064 G_IO_ERROR_NOT_SUPPORTED,
2065 _("Unable to find or create trash directory"));
2066 return FALSE;
2069 basename = g_path_get_basename (local->filename);
2070 i = 1;
2071 trashname = NULL;
2072 infofile = NULL;
2073 do {
2074 g_free (trashname);
2075 g_free (infofile);
2077 trashname = get_unique_filename (basename, i++);
2078 infoname = g_strconcat (trashname, ".trashinfo", NULL);
2079 infofile = g_build_filename (infodir, infoname, NULL);
2080 g_free (infoname);
2082 fd = g_open (infofile, O_CREAT | O_EXCL, 0666);
2083 } while (fd == -1 && errno == EEXIST);
2085 g_free (basename);
2086 g_free (infodir);
2088 if (fd == -1)
2090 int errsv = errno;
2092 g_free (filesdir);
2093 g_free (topdir);
2094 g_free (trashname);
2095 g_free (infofile);
2097 g_set_error (error, G_IO_ERROR,
2098 g_io_error_from_errno (errsv),
2099 _("Unable to create trashing info file: %s"),
2100 g_strerror (errsv));
2101 return FALSE;
2104 (void) g_close (fd, NULL);
2106 /* Write the full content of the info file before trashing to make
2107 * sure someone doesn't read an empty file. See #749314
2110 /* Use absolute names for homedir */
2111 if (is_homedir_trash)
2112 original_name = g_strdup (local->filename);
2113 else
2114 original_name = try_make_relative (local->filename, topdir);
2115 original_name_escaped = g_uri_escape_string (original_name, "/", FALSE);
2117 g_free (original_name);
2118 g_free (topdir);
2121 time_t t;
2122 struct tm now;
2123 t = time (NULL);
2124 localtime_r (&t, &now);
2125 delete_time[0] = 0;
2126 strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
2129 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2130 original_name_escaped, delete_time);
2132 g_file_set_contents (infofile, data, -1, NULL);
2134 /* TODO: Maybe we should verify that you can delete the file from the trash
2135 before moving it? OTOH, that is hard, as it needs a recursive scan */
2137 trashfile = g_build_filename (filesdir, trashname, NULL);
2139 g_free (filesdir);
2141 if (g_rename (local->filename, trashfile) == -1)
2143 int errsv = errno;
2145 g_unlink (infofile);
2147 g_free (trashname);
2148 g_free (infofile);
2149 g_free (trashfile);
2151 if (errsv == EXDEV)
2152 /* The trash dir was actually on another fs anyway!?
2153 This can happen when the same device is mounted multiple
2154 times, or with bind mounts of the same fs. */
2155 g_set_error (error, G_IO_ERROR,
2156 G_IO_ERROR_NOT_SUPPORTED,
2157 _("Unable to trash file: %s"),
2158 g_strerror (errsv));
2159 else
2160 g_set_error (error, G_IO_ERROR,
2161 g_io_error_from_errno (errsv),
2162 _("Unable to trash file: %s"),
2163 g_strerror (errsv));
2164 return FALSE;
2167 vfs = g_vfs_get_default ();
2168 class = G_VFS_GET_CLASS (vfs);
2169 if (class->local_file_moved)
2170 class->local_file_moved (vfs, local->filename, trashfile);
2172 g_free (trashfile);
2174 /* TODO: Do we need to update mtime/atime here after the move? */
2176 g_free (infofile);
2177 g_free (data);
2179 g_free (original_name_escaped);
2180 g_free (trashname);
2182 return TRUE;
2184 #else /* G_OS_WIN32 */
2185 gboolean
2186 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2188 return FALSE; /* XXX ??? */
2191 static gboolean
2192 g_local_file_trash (GFile *file,
2193 GCancellable *cancellable,
2194 GError **error)
2196 GLocalFile *local = G_LOCAL_FILE (file);
2197 SHFILEOPSTRUCTW op = {0};
2198 gboolean success;
2199 wchar_t *wfilename;
2200 long len;
2202 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2203 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2204 wfilename = g_renew (wchar_t, wfilename, len + 2);
2205 wfilename[len + 1] = 0;
2207 op.wFunc = FO_DELETE;
2208 op.pFrom = wfilename;
2209 op.fFlags = FOF_ALLOWUNDO;
2211 success = SHFileOperationW (&op) == 0;
2213 if (success && op.fAnyOperationsAborted)
2215 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2216 g_cancellable_cancel (cancellable);
2217 g_set_error (error, G_IO_ERROR,
2218 G_IO_ERROR_CANCELLED,
2219 _("Unable to trash file: %s"),
2220 _("Operation was cancelled"));
2221 success = FALSE;
2223 else if (!success)
2224 g_set_error (error, G_IO_ERROR,
2225 G_IO_ERROR_FAILED,
2226 _("Unable to trash file: %s"),
2227 _("internal error"));
2229 g_free (wfilename);
2230 return success;
2232 #endif /* G_OS_WIN32 */
2234 static gboolean
2235 g_local_file_make_directory (GFile *file,
2236 GCancellable *cancellable,
2237 GError **error)
2239 GLocalFile *local = G_LOCAL_FILE (file);
2241 if (g_mkdir (local->filename, 0777) == -1)
2243 int errsv = errno;
2245 if (errsv == EINVAL)
2246 /* This must be an invalid filename, on e.g. FAT */
2247 g_set_error_literal (error, G_IO_ERROR,
2248 G_IO_ERROR_INVALID_FILENAME,
2249 _("Invalid filename"));
2250 else
2251 g_set_error (error, G_IO_ERROR,
2252 g_io_error_from_errno (errsv),
2253 _("Error creating directory: %s"),
2254 g_strerror (errsv));
2255 return FALSE;
2258 return TRUE;
2261 static gboolean
2262 g_local_file_make_symbolic_link (GFile *file,
2263 const char *symlink_value,
2264 GCancellable *cancellable,
2265 GError **error)
2267 #ifdef HAVE_SYMLINK
2268 GLocalFile *local = G_LOCAL_FILE (file);
2270 if (symlink (symlink_value, local->filename) == -1)
2272 int errsv = errno;
2274 if (errsv == EINVAL)
2275 /* This must be an invalid filename, on e.g. FAT */
2276 g_set_error_literal (error, G_IO_ERROR,
2277 G_IO_ERROR_INVALID_FILENAME,
2278 _("Invalid filename"));
2279 else if (errsv == EPERM)
2280 g_set_error (error, G_IO_ERROR,
2281 G_IO_ERROR_NOT_SUPPORTED,
2282 _("Filesystem does not support symbolic links"));
2283 else
2284 g_set_error (error, G_IO_ERROR,
2285 g_io_error_from_errno (errsv),
2286 _("Error making symbolic link: %s"),
2287 g_strerror (errsv));
2288 return FALSE;
2290 return TRUE;
2291 #else
2292 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
2293 return FALSE;
2294 #endif
2298 static gboolean
2299 g_local_file_copy (GFile *source,
2300 GFile *destination,
2301 GFileCopyFlags flags,
2302 GCancellable *cancellable,
2303 GFileProgressCallback progress_callback,
2304 gpointer progress_callback_data,
2305 GError **error)
2307 /* Fall back to default copy */
2308 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2309 return FALSE;
2312 static gboolean
2313 g_local_file_move (GFile *source,
2314 GFile *destination,
2315 GFileCopyFlags flags,
2316 GCancellable *cancellable,
2317 GFileProgressCallback progress_callback,
2318 gpointer progress_callback_data,
2319 GError **error)
2321 GLocalFile *local_source, *local_destination;
2322 GStatBuf statbuf;
2323 gboolean destination_exist, source_is_dir;
2324 char *backup_name;
2325 int res;
2326 off_t source_size;
2327 GVfsClass *class;
2328 GVfs *vfs;
2330 if (!G_IS_LOCAL_FILE (source) ||
2331 !G_IS_LOCAL_FILE (destination))
2333 /* Fall back to default move */
2334 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2335 return FALSE;
2338 local_source = G_LOCAL_FILE (source);
2339 local_destination = G_LOCAL_FILE (destination);
2341 res = g_lstat (local_source->filename, &statbuf);
2342 if (res == -1)
2344 int errsv = errno;
2346 g_set_error (error, G_IO_ERROR,
2347 g_io_error_from_errno (errsv),
2348 _("Error moving file: %s"),
2349 g_strerror (errsv));
2350 return FALSE;
2353 source_is_dir = S_ISDIR (statbuf.st_mode);
2354 source_size = statbuf.st_size;
2356 destination_exist = FALSE;
2357 res = g_lstat (local_destination->filename, &statbuf);
2358 if (res == 0)
2360 destination_exist = TRUE; /* Target file exists */
2362 if (flags & G_FILE_COPY_OVERWRITE)
2364 /* Always fail on dirs, even with overwrite */
2365 if (S_ISDIR (statbuf.st_mode))
2367 if (source_is_dir)
2368 g_set_error_literal (error,
2369 G_IO_ERROR,
2370 G_IO_ERROR_WOULD_MERGE,
2371 _("Can't move directory over directory"));
2372 else
2373 g_set_error_literal (error,
2374 G_IO_ERROR,
2375 G_IO_ERROR_IS_DIRECTORY,
2376 _("Can't copy over directory"));
2377 return FALSE;
2380 else
2382 g_set_error_literal (error,
2383 G_IO_ERROR,
2384 G_IO_ERROR_EXISTS,
2385 _("Target file exists"));
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_error (error, G_IO_ERROR,
2441 g_io_error_from_errno (errsv),
2442 _("Error moving file: %s"),
2443 g_strerror (errsv));
2444 return FALSE;
2447 vfs = g_vfs_get_default ();
2448 class = G_VFS_GET_CLASS (vfs);
2449 if (class->local_file_moved)
2450 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2452 /* Make sure we send full copied size */
2453 if (progress_callback)
2454 progress_callback (source_size, source_size, progress_callback_data);
2456 return TRUE;
2459 #ifdef G_OS_WIN32
2461 gboolean
2462 g_local_file_is_remote (const gchar *filename)
2464 return FALSE;
2467 #else
2469 static gboolean
2470 is_remote_fs (const gchar *filename)
2472 const char *fsname = NULL;
2474 #ifdef USE_STATFS
2475 struct statfs statfs_buffer;
2476 int statfs_result = 0;
2478 #if STATFS_ARGS == 2
2479 statfs_result = statfs (filename, &statfs_buffer);
2480 #elif STATFS_ARGS == 4
2481 statfs_result = statfs (filename, &statfs_buffer, sizeof (statfs_buffer), 0);
2482 #endif
2484 #elif defined(USE_STATVFS)
2485 struct statvfs statfs_buffer;
2486 int statfs_result = 0;
2488 statfs_result = statvfs (filename, &statfs_buffer);
2489 #else
2490 return FALSE;
2491 #endif
2493 if (statfs_result == -1)
2494 return FALSE;
2496 #ifdef USE_STATFS
2497 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
2498 fsname = statfs_buffer.f_fstypename;
2499 #else
2500 fsname = get_fs_type (statfs_buffer.f_type);
2501 #endif
2503 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
2504 fsname = statfs_buffer.f_basetype;
2505 #endif
2507 if (fsname != NULL)
2509 if (strcmp (fsname, "nfs") == 0)
2510 return TRUE;
2511 if (strcmp (fsname, "nfs4") == 0)
2512 return TRUE;
2515 return FALSE;
2518 gboolean
2519 g_local_file_is_remote (const gchar *filename)
2521 static gboolean remote_home;
2522 static gsize initialized;
2523 const gchar *home;
2525 home = g_get_home_dir ();
2526 if (path_has_prefix (filename, home))
2528 if (g_once_init_enter (&initialized))
2530 remote_home = is_remote_fs (home);
2531 g_once_init_leave (&initialized, TRUE);
2533 return remote_home;
2536 return FALSE;
2538 #endif /* !G_OS_WIN32 */
2540 static GFileMonitor*
2541 g_local_file_monitor_dir (GFile *file,
2542 GFileMonitorFlags flags,
2543 GCancellable *cancellable,
2544 GError **error)
2546 GLocalFile *local_file = G_LOCAL_FILE (file);
2548 return g_local_file_monitor_new_for_path (local_file->filename, TRUE, flags, error);
2551 static GFileMonitor*
2552 g_local_file_monitor_file (GFile *file,
2553 GFileMonitorFlags flags,
2554 GCancellable *cancellable,
2555 GError **error)
2557 GLocalFile *local_file = G_LOCAL_FILE (file);
2559 return g_local_file_monitor_new_for_path (local_file->filename, FALSE, flags, error);
2562 /* Here is the GLocalFile implementation of g_file_measure_disk_usage().
2564 * If available, we use fopenat() in preference to filenames for
2565 * efficiency and safety reasons. We know that fopenat() is available
2566 * based on if AT_FDCWD is defined. POSIX guarantees that this will be
2567 * defined as a macro.
2569 * We use a linked list of stack-allocated GSList nodes in order to be
2570 * able to reconstruct the filename for error messages. We actually
2571 * pass the filename to operate on through the top node of the list.
2573 * In case we're using openat(), this top filename will be a basename
2574 * which should be opened in the directory which has also had its fd
2575 * passed along. If we're not using openat() then it will be a full
2576 * absolute filename.
2579 static gboolean
2580 g_local_file_measure_size_error (GFileMeasureFlags flags,
2581 gint saved_errno,
2582 GSList *name,
2583 GError **error)
2585 /* Only report an error if we were at the toplevel or if the caller
2586 * requested reporting of all errors.
2588 if ((name->next == NULL) || (flags & G_FILE_MEASURE_REPORT_ANY_ERROR))
2590 GString *filename;
2591 GSList *node;
2593 /* Skip some work if there is no error return */
2594 if (!error)
2595 return FALSE;
2597 #ifdef AT_FDCWD
2598 /* If using openat() we need to rebuild the filename for the message */
2599 filename = g_string_new (name->data);
2600 for (node = name->next; node; node = node->next)
2602 gchar *utf8;
2604 g_string_prepend_c (filename, G_DIR_SEPARATOR);
2605 utf8 = g_filename_display_name (node->data);
2606 g_string_prepend (filename, utf8);
2607 g_free (utf8);
2609 #else
2611 gchar *utf8;
2613 /* Otherwise, we already have it, so just use it. */
2614 node = name;
2615 filename = g_string_new (NULL);
2616 utf8 = g_filename_display_name (node->data);
2617 g_string_append (filename, utf8);
2618 g_free (utf8);
2620 #endif
2622 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
2623 _("Could not determine the disk usage of %s: %s"),
2624 filename->str, g_strerror (saved_errno));
2626 g_string_free (filename, TRUE);
2628 return FALSE;
2631 else
2632 /* We're not reporting this error... */
2633 return TRUE;
2636 typedef struct
2638 GFileMeasureFlags flags;
2639 dev_t contained_on;
2640 GCancellable *cancellable;
2642 GFileMeasureProgressCallback progress_callback;
2643 gpointer progress_data;
2645 guint64 disk_usage;
2646 guint64 num_dirs;
2647 guint64 num_files;
2649 guint64 last_progress_report;
2650 } MeasureState;
2652 static gboolean
2653 g_local_file_measure_size_of_contents (gint fd,
2654 GSList *dir_name,
2655 MeasureState *state,
2656 GError **error);
2658 static gboolean
2659 g_local_file_measure_size_of_file (gint parent_fd,
2660 GSList *name,
2661 MeasureState *state,
2662 GError **error)
2664 GLocalFileStat buf;
2666 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2667 return FALSE;
2669 #if defined (AT_FDCWD)
2670 if (fstatat (parent_fd, name->data, &buf, AT_SYMLINK_NOFOLLOW) != 0)
2671 return g_local_file_measure_size_error (state->flags, errno, name, error);
2672 #elif defined (HAVE_LSTAT) || !defined (G_OS_WIN32)
2673 if (g_lstat (name->data, &buf) != 0)
2674 return g_local_file_measure_size_error (state->flags, errno, name, error);
2675 #else
2677 const char *filename = (const gchar *) name->data;
2678 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
2679 int retval;
2680 int save_errno;
2681 int len;
2683 if (wfilename == NULL)
2684 return g_local_file_measure_size_error (state->flags, errno, name, error);
2686 len = wcslen (wfilename);
2687 while (len > 0 && G_IS_DIR_SEPARATOR (wfilename[len-1]))
2688 len--;
2689 if (len > 0 &&
2690 (!g_path_is_absolute (filename) || len > g_path_skip_root (filename) - filename))
2691 wfilename[len] = '\0';
2693 retval = _wstati64 (wfilename, &buf);
2694 save_errno = errno;
2696 g_free (wfilename);
2698 errno = save_errno;
2699 if (retval != 0)
2700 return g_local_file_measure_size_error (state->flags, errno, name, error);
2702 #endif
2704 if (name->next)
2706 /* If not at the toplevel, check for a device boundary. */
2708 if (state->flags & G_FILE_MEASURE_NO_XDEV)
2709 if (state->contained_on != buf.st_dev)
2710 return TRUE;
2712 else
2714 /* If, however, this is the toplevel, set the device number so
2715 * that recursive invocations can compare against it.
2717 state->contained_on = buf.st_dev;
2720 #if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
2721 if (~state->flags & G_FILE_MEASURE_APPARENT_SIZE)
2722 state->disk_usage += buf.st_blocks * G_GUINT64_CONSTANT (512);
2723 else
2724 #endif
2725 state->disk_usage += buf.st_size;
2727 if (S_ISDIR (buf.st_mode))
2728 state->num_dirs++;
2729 else
2730 state->num_files++;
2732 if (state->progress_callback)
2734 /* We could attempt to do some cleverness here in order to avoid
2735 * calling clock_gettime() so much, but we're doing stats and opens
2736 * all over the place already...
2738 if (state->last_progress_report)
2740 guint64 now;
2742 now = g_get_monotonic_time ();
2744 if (state->last_progress_report + 200 * G_TIME_SPAN_MILLISECOND < now)
2746 (* state->progress_callback) (TRUE,
2747 state->disk_usage, state->num_dirs, state->num_files,
2748 state->progress_data);
2749 state->last_progress_report = now;
2752 else
2754 /* We must do an initial report to inform that more reports
2755 * will be coming.
2757 (* state->progress_callback) (TRUE, 0, 0, 0, state->progress_data);
2758 state->last_progress_report = g_get_monotonic_time ();
2762 if (S_ISDIR (buf.st_mode))
2764 int dir_fd = -1;
2766 if (g_cancellable_set_error_if_cancelled (state->cancellable, error))
2767 return FALSE;
2769 #ifdef AT_FDCWD
2770 #ifdef HAVE_OPEN_O_DIRECTORY
2771 dir_fd = openat (parent_fd, name->data, O_RDONLY|O_DIRECTORY);
2772 #else
2773 dir_fd = openat (parent_fd, name->data, O_RDONLY);
2774 #endif
2775 if (dir_fd < 0)
2776 return g_local_file_measure_size_error (state->flags, errno, name, error);
2777 #endif
2779 if (!g_local_file_measure_size_of_contents (dir_fd, name, state, error))
2780 return FALSE;
2783 return TRUE;
2786 static gboolean
2787 g_local_file_measure_size_of_contents (gint fd,
2788 GSList *dir_name,
2789 MeasureState *state,
2790 GError **error)
2792 gboolean success = TRUE;
2793 const gchar *name;
2794 GDir *dir;
2796 #ifdef AT_FDCWD
2798 /* If this fails, we want to preserve the errno from fopendir() */
2799 DIR *dirp;
2800 dirp = fdopendir (fd);
2801 dir = dirp ? GLIB_PRIVATE_CALL(g_dir_new_from_dirp) (dirp) : NULL;
2803 #else
2804 dir = GLIB_PRIVATE_CALL(g_dir_open_with_errno) (dir_name->data, 0);
2805 #endif
2807 if (dir == NULL)
2809 gint saved_errno = errno;
2811 #ifdef AT_FDCWD
2812 close (fd);
2813 #endif
2815 return g_local_file_measure_size_error (state->flags, saved_errno, dir_name, error);
2818 while (success && (name = g_dir_read_name (dir)))
2820 GSList node;
2822 node.next = dir_name;
2823 #ifdef AT_FDCWD
2824 node.data = (gchar *) name;
2825 #else
2826 node.data = g_build_filename (dir_name->data, name, NULL);
2827 #endif
2829 success = g_local_file_measure_size_of_file (fd, &node, state, error);
2831 #ifndef AT_FDCWD
2832 g_free (node.data);
2833 #endif
2836 g_dir_close (dir);
2838 return success;
2841 static gboolean
2842 g_local_file_measure_disk_usage (GFile *file,
2843 GFileMeasureFlags flags,
2844 GCancellable *cancellable,
2845 GFileMeasureProgressCallback progress_callback,
2846 gpointer progress_data,
2847 guint64 *disk_usage,
2848 guint64 *num_dirs,
2849 guint64 *num_files,
2850 GError **error)
2852 GLocalFile *local_file = G_LOCAL_FILE (file);
2853 MeasureState state = { 0, };
2854 gint root_fd = -1;
2855 GSList node;
2857 state.flags = flags;
2858 state.cancellable = cancellable;
2859 state.progress_callback = progress_callback;
2860 state.progress_data = progress_data;
2862 #ifdef AT_FDCWD
2863 root_fd = AT_FDCWD;
2864 #endif
2866 node.data = local_file->filename;
2867 node.next = NULL;
2869 if (!g_local_file_measure_size_of_file (root_fd, &node, &state, error))
2870 return FALSE;
2872 if (disk_usage)
2873 *disk_usage = state.disk_usage;
2875 if (num_dirs)
2876 *num_dirs = state.num_dirs;
2878 if (num_files)
2879 *num_files = state.num_files;
2881 return TRUE;
2884 static void
2885 g_local_file_file_iface_init (GFileIface *iface)
2887 iface->dup = g_local_file_dup;
2888 iface->hash = g_local_file_hash;
2889 iface->equal = g_local_file_equal;
2890 iface->is_native = g_local_file_is_native;
2891 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2892 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2893 iface->get_basename = g_local_file_get_basename;
2894 iface->get_path = g_local_file_get_path;
2895 iface->get_uri = g_local_file_get_uri;
2896 iface->get_parse_name = g_local_file_get_parse_name;
2897 iface->get_parent = g_local_file_get_parent;
2898 iface->prefix_matches = g_local_file_prefix_matches;
2899 iface->get_relative_path = g_local_file_get_relative_path;
2900 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2901 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2902 iface->set_display_name = g_local_file_set_display_name;
2903 iface->enumerate_children = g_local_file_enumerate_children;
2904 iface->query_info = g_local_file_query_info;
2905 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2906 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2907 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2908 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2909 iface->set_attribute = g_local_file_set_attribute;
2910 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2911 iface->read_fn = g_local_file_read;
2912 iface->append_to = g_local_file_append_to;
2913 iface->create = g_local_file_create;
2914 iface->replace = g_local_file_replace;
2915 iface->open_readwrite = g_local_file_open_readwrite;
2916 iface->create_readwrite = g_local_file_create_readwrite;
2917 iface->replace_readwrite = g_local_file_replace_readwrite;
2918 iface->delete_file = g_local_file_delete;
2919 iface->trash = g_local_file_trash;
2920 iface->make_directory = g_local_file_make_directory;
2921 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2922 iface->copy = g_local_file_copy;
2923 iface->move = g_local_file_move;
2924 iface->monitor_dir = g_local_file_monitor_dir;
2925 iface->monitor_file = g_local_file_monitor_file;
2926 iface->measure_disk_usage = g_local_file_measure_disk_usage;
2928 iface->supports_thread_contexts = TRUE;