docs: Fix GApplicationCommandLine typo
[glib.git] / gio / glocalfile.c
blob176817d7094f256ef3b55faf6f1546997383cea6
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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: Alexander Larsson <alexl@redhat.com>
23 #include "config.h"
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
34 #if HAVE_SYS_STATFS_H
35 #include <sys/statfs.h>
36 #endif
37 #if HAVE_SYS_STATVFS_H
38 #include <sys/statvfs.h>
39 #endif
40 #if HAVE_SYS_VFS_H
41 #include <sys/vfs.h>
42 #elif HAVE_SYS_MOUNT_H
43 #if HAVE_SYS_PARAM_H
44 #include <sys/param.h>
45 #endif
46 #include <sys/mount.h>
47 #endif
49 #ifndef O_BINARY
50 #define O_BINARY 0
51 #endif
53 #include "gfileattribute.h"
54 #include "glocalfile.h"
55 #include "glocalfileinfo.h"
56 #include "glocalfileenumerator.h"
57 #include "glocalfileinputstream.h"
58 #include "glocalfileoutputstream.h"
59 #include "glocalfileiostream.h"
60 #include "glocaldirectorymonitor.h"
61 #include "glocalfilemonitor.h"
62 #include "gmountprivate.h"
63 #include "gunixmounts.h"
64 #include "gioerror.h"
65 #include <glib/gstdio.h>
66 #include "glibintl.h"
68 #ifdef G_OS_WIN32
69 #define _WIN32_WINNT 0x0500
70 #include <windows.h>
71 #include <io.h>
72 #include <direct.h>
74 #ifndef FILE_READ_ONLY_VOLUME
75 #define FILE_READ_ONLY_VOLUME 0x00080000
76 #endif
78 #ifndef S_ISDIR
79 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
80 #endif
81 #ifndef S_ISLNK
82 #define S_ISLNK(m) (0)
83 #endif
84 #endif
87 static void g_local_file_file_iface_init (GFileIface *iface);
89 static GFileAttributeInfoList *local_writable_attributes = NULL;
90 static /* GFileAttributeInfoList * */ gsize local_writable_namespaces = 0;
92 struct _GLocalFile
94 GObject parent_instance;
96 char *filename;
99 #define g_local_file_get_type _g_local_file_get_type
100 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
101 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
102 g_local_file_file_iface_init))
104 static char *find_mountpoint_for (const char *file, dev_t dev);
106 static void
107 g_local_file_finalize (GObject *object)
109 GLocalFile *local;
111 local = G_LOCAL_FILE (object);
113 g_free (local->filename);
115 G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
118 static void
119 g_local_file_class_init (GLocalFileClass *klass)
121 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
122 GFileAttributeInfoList *list;
124 gobject_class->finalize = g_local_file_finalize;
126 /* Set up attribute lists */
128 /* Writable attributes: */
130 list = g_file_attribute_info_list_new ();
132 g_file_attribute_info_list_add (list,
133 G_FILE_ATTRIBUTE_UNIX_MODE,
134 G_FILE_ATTRIBUTE_TYPE_UINT32,
135 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
136 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
138 #ifdef HAVE_CHOWN
139 g_file_attribute_info_list_add (list,
140 G_FILE_ATTRIBUTE_UNIX_UID,
141 G_FILE_ATTRIBUTE_TYPE_UINT32,
142 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
143 g_file_attribute_info_list_add (list,
144 G_FILE_ATTRIBUTE_UNIX_GID,
145 G_FILE_ATTRIBUTE_TYPE_UINT32,
146 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
147 #endif
149 #ifdef HAVE_SYMLINK
150 g_file_attribute_info_list_add (list,
151 G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
152 G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
154 #endif
156 #ifdef HAVE_UTIMES
157 g_file_attribute_info_list_add (list,
158 G_FILE_ATTRIBUTE_TIME_MODIFIED,
159 G_FILE_ATTRIBUTE_TYPE_UINT64,
160 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
161 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
162 g_file_attribute_info_list_add (list,
163 G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
164 G_FILE_ATTRIBUTE_TYPE_UINT32,
165 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
166 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
167 /* When copying, the target file is accessed. Replicating
168 * the source access time does not make sense in this case.
170 g_file_attribute_info_list_add (list,
171 G_FILE_ATTRIBUTE_TIME_ACCESS,
172 G_FILE_ATTRIBUTE_TYPE_UINT64,
173 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
174 g_file_attribute_info_list_add (list,
175 G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
176 G_FILE_ATTRIBUTE_TYPE_UINT32,
177 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
178 #endif
180 local_writable_attributes = list;
183 static void
184 g_local_file_init (GLocalFile *local)
189 static char *
190 canonicalize_filename (const char *filename)
192 char *canon, *start, *p, *q;
193 char *cwd;
194 int i;
196 if (!g_path_is_absolute (filename))
198 cwd = g_get_current_dir ();
199 canon = g_build_filename (cwd, filename, NULL);
200 g_free (cwd);
202 else
203 canon = g_strdup (filename);
205 start = (char *)g_path_skip_root (canon);
207 if (start == NULL)
209 /* This shouldn't really happen, as g_get_current_dir() should
210 return an absolute pathname, but bug 573843 shows this is
211 not always happening */
212 g_free (canon);
213 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
216 /* POSIX allows double slashes at the start to
217 * mean something special (as does windows too).
218 * So, "//" != "/", but more than two slashes
219 * is treated as "/".
221 i = 0;
222 for (p = start - 1;
223 (p >= canon) &&
224 G_IS_DIR_SEPARATOR (*p);
225 p--)
226 i++;
227 if (i > 2)
229 i -= 1;
230 start -= i;
231 memmove (start, start+i, strlen (start+i)+1);
234 p = start;
235 while (*p != 0)
237 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
239 memmove (p, p+1, strlen (p+1)+1);
241 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
243 q = p + 2;
244 /* Skip previous separator */
245 p = p - 2;
246 if (p < start)
247 p = start;
248 while (p > start && !G_IS_DIR_SEPARATOR (*p))
249 p--;
250 if (G_IS_DIR_SEPARATOR (*p))
251 *p++ = G_DIR_SEPARATOR;
252 memmove (p, q, strlen (q)+1);
254 else
256 /* Skip until next separator */
257 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
258 p++;
260 if (*p != 0)
262 /* Canonicalize one separator */
263 *p++ = G_DIR_SEPARATOR;
267 /* Remove additional separators */
268 q = p;
269 while (*q && G_IS_DIR_SEPARATOR (*q))
270 q++;
272 if (p != q)
273 memmove (p, q, strlen (q)+1);
276 /* Remove trailing slashes */
277 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
278 *(p-1) = 0;
280 return canon;
283 GFile *
284 _g_local_file_new (const char *filename)
286 GLocalFile *local;
288 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
289 local->filename = canonicalize_filename (filename);
291 return G_FILE (local);
294 static gboolean
295 g_local_file_is_native (GFile *file)
297 return TRUE;
300 static gboolean
301 g_local_file_has_uri_scheme (GFile *file,
302 const char *uri_scheme)
304 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
307 static char *
308 g_local_file_get_uri_scheme (GFile *file)
310 return g_strdup ("file");
313 static char *
314 g_local_file_get_basename (GFile *file)
316 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
319 static char *
320 g_local_file_get_path (GFile *file)
322 return g_strdup (G_LOCAL_FILE (file)->filename);
325 static char *
326 g_local_file_get_uri (GFile *file)
328 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
331 static gboolean
332 get_filename_charset (const gchar **filename_charset)
334 const gchar **charsets;
335 gboolean is_utf8;
337 is_utf8 = g_get_filename_charsets (&charsets);
339 if (filename_charset)
340 *filename_charset = charsets[0];
342 return is_utf8;
345 static gboolean
346 name_is_valid_for_display (const char *string,
347 gboolean is_valid_utf8)
349 char c;
351 if (!is_valid_utf8 &&
352 !g_utf8_validate (string, -1, NULL))
353 return FALSE;
355 while ((c = *string++) != 0)
357 if (g_ascii_iscntrl (c))
358 return FALSE;
361 return TRUE;
364 static char *
365 g_local_file_get_parse_name (GFile *file)
367 const char *filename;
368 char *parse_name;
369 const gchar *charset;
370 char *utf8_filename;
371 char *roundtripped_filename;
372 gboolean free_utf8_filename;
373 gboolean is_valid_utf8;
374 char *escaped_path;
376 filename = G_LOCAL_FILE (file)->filename;
377 if (get_filename_charset (&charset))
379 utf8_filename = (char *)filename;
380 free_utf8_filename = FALSE;
381 is_valid_utf8 = FALSE; /* Can't guarantee this */
383 else
385 utf8_filename = g_convert (filename, -1,
386 "UTF-8", charset, NULL, NULL, NULL);
387 free_utf8_filename = TRUE;
388 is_valid_utf8 = TRUE;
390 if (utf8_filename != NULL)
392 /* Make sure we can roundtrip: */
393 roundtripped_filename = g_convert (utf8_filename, -1,
394 charset, "UTF-8", NULL, NULL, NULL);
396 if (roundtripped_filename == NULL ||
397 strcmp (filename, roundtripped_filename) != 0)
399 g_free (utf8_filename);
400 utf8_filename = NULL;
403 g_free (roundtripped_filename);
407 if (utf8_filename != NULL &&
408 name_is_valid_for_display (utf8_filename, is_valid_utf8))
410 if (free_utf8_filename)
411 parse_name = utf8_filename;
412 else
413 parse_name = g_strdup (utf8_filename);
415 else
417 escaped_path = g_uri_escape_string (filename,
418 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
419 TRUE);
420 parse_name = g_strconcat ("file://",
421 (*escaped_path != '/') ? "/" : "",
422 escaped_path,
423 NULL);
425 g_free (escaped_path);
427 if (free_utf8_filename)
428 g_free (utf8_filename);
431 return parse_name;
434 static GFile *
435 g_local_file_get_parent (GFile *file)
437 GLocalFile *local = G_LOCAL_FILE (file);
438 const char *non_root;
439 char *dirname;
440 GFile *parent;
442 /* Check for root */
443 non_root = g_path_skip_root (local->filename);
444 if (*non_root == 0)
445 return NULL;
447 dirname = g_path_get_dirname (local->filename);
448 parent = _g_local_file_new (dirname);
449 g_free (dirname);
450 return parent;
453 static GFile *
454 g_local_file_dup (GFile *file)
456 GLocalFile *local = G_LOCAL_FILE (file);
458 return _g_local_file_new (local->filename);
461 static guint
462 g_local_file_hash (GFile *file)
464 GLocalFile *local = G_LOCAL_FILE (file);
466 return g_str_hash (local->filename);
469 static gboolean
470 g_local_file_equal (GFile *file1,
471 GFile *file2)
473 GLocalFile *local1 = G_LOCAL_FILE (file1);
474 GLocalFile *local2 = G_LOCAL_FILE (file2);
476 return g_str_equal (local1->filename, local2->filename);
479 static const char *
480 match_prefix (const char *path,
481 const char *prefix)
483 int prefix_len;
485 prefix_len = strlen (prefix);
486 if (strncmp (path, prefix, prefix_len) != 0)
487 return NULL;
489 /* Handle the case where prefix is the root, so that
490 * the IS_DIR_SEPRARATOR check below works */
491 if (prefix_len > 0 &&
492 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
493 prefix_len--;
495 return path + prefix_len;
498 static gboolean
499 g_local_file_prefix_matches (GFile *parent,
500 GFile *descendant)
502 GLocalFile *parent_local = G_LOCAL_FILE (parent);
503 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
504 const char *remainder;
506 remainder = match_prefix (descendant_local->filename, parent_local->filename);
507 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
508 return TRUE;
509 return FALSE;
512 static char *
513 g_local_file_get_relative_path (GFile *parent,
514 GFile *descendant)
516 GLocalFile *parent_local = G_LOCAL_FILE (parent);
517 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
518 const char *remainder;
520 remainder = match_prefix (descendant_local->filename, parent_local->filename);
522 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
523 return g_strdup (remainder + 1);
524 return NULL;
527 static GFile *
528 g_local_file_resolve_relative_path (GFile *file,
529 const char *relative_path)
531 GLocalFile *local = G_LOCAL_FILE (file);
532 char *filename;
533 GFile *child;
535 if (g_path_is_absolute (relative_path))
536 return _g_local_file_new (relative_path);
538 filename = g_build_filename (local->filename, relative_path, NULL);
539 child = _g_local_file_new (filename);
540 g_free (filename);
542 return child;
545 static GFileEnumerator *
546 g_local_file_enumerate_children (GFile *file,
547 const char *attributes,
548 GFileQueryInfoFlags flags,
549 GCancellable *cancellable,
550 GError **error)
552 GLocalFile *local = G_LOCAL_FILE (file);
553 return _g_local_file_enumerator_new (local,
554 attributes, flags,
555 cancellable, error);
558 static GFile *
559 g_local_file_get_child_for_display_name (GFile *file,
560 const char *display_name,
561 GError **error)
563 GFile *new_file;
564 char *basename;
566 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
567 if (basename == NULL)
569 g_set_error (error, G_IO_ERROR,
570 G_IO_ERROR_INVALID_FILENAME,
571 _("Invalid filename %s"), display_name);
572 return NULL;
575 new_file = g_file_get_child (file, basename);
576 g_free (basename);
578 return new_file;
581 #if defined(USE_STATFS) && !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
582 static const char *
583 get_fs_type (long f_type)
585 /* filesystem ids taken from linux manpage */
586 switch (f_type)
588 case 0xadf5:
589 return "adfs";
590 case 0x5346414f:
591 return "afs";
592 case 0x0187:
593 return "autofs";
594 case 0xADFF:
595 return "affs";
596 case 0x42465331:
597 return "befs";
598 case 0x1BADFACE:
599 return "bfs";
600 case 0x9123683E:
601 return "btrfs";
602 case 0xFF534D42:
603 return "cifs";
604 case 0x73757245:
605 return "coda";
606 case 0x012FF7B7:
607 return "coh";
608 case 0x28cd3d45:
609 return "cramfs";
610 case 0x1373:
611 return "devfs";
612 case 0x00414A53:
613 return "efs";
614 case 0x137D:
615 return "ext";
616 case 0xEF51:
617 return "ext2";
618 case 0xEF53:
619 return "ext3/ext4";
620 case 0x4244:
621 return "hfs";
622 case 0xF995E849:
623 return "hpfs";
624 case 0x958458f6:
625 return "hugetlbfs";
626 case 0x9660:
627 return "isofs";
628 case 0x72b6:
629 return "jffs2";
630 case 0x3153464a:
631 return "jfs";
632 case 0x137F:
633 return "minix";
634 case 0x138F:
635 return "minix2";
636 case 0x2468:
637 return "minix2";
638 case 0x2478:
639 return "minix22";
640 case 0x4d44:
641 return "msdos";
642 case 0x564c:
643 return "ncp";
644 case 0x6969:
645 return "nfs";
646 case 0x5346544e:
647 return "ntfs";
648 case 0x9fa1:
649 return "openprom";
650 case 0x9fa0:
651 return "proc";
652 case 0x002f:
653 return "qnx4";
654 case 0x52654973:
655 return "reiserfs";
656 case 0x7275:
657 return "romfs";
658 case 0x517B:
659 return "smb";
660 case 0x73717368:
661 return "squashfs";
662 case 0x012FF7B6:
663 return "sysv2";
664 case 0x012FF7B5:
665 return "sysv4";
666 case 0x01021994:
667 return "tmpfs";
668 case 0x15013346:
669 return "udf";
670 case 0x00011954:
671 return "ufs";
672 case 0x9fa2:
673 return "usbdevice";
674 case 0xa501FCF5:
675 return "vxfs";
676 case 0x012FF7B4:
677 return "xenix";
678 case 0x58465342:
679 return "xfs";
680 case 0x012FD16D:
681 return "xiafs";
682 case 0x52345362:
683 return "reiser4";
684 default:
685 return NULL;
688 #endif
690 #ifndef G_OS_WIN32
692 G_LOCK_DEFINE_STATIC(mount_info_hash);
693 static GHashTable *mount_info_hash = NULL;
694 static guint64 mount_info_hash_cache_time = 0;
696 typedef enum {
697 MOUNT_INFO_READONLY = 1<<0
698 } MountInfo;
700 static gboolean
701 device_equal (gconstpointer v1,
702 gconstpointer v2)
704 return *(dev_t *)v1 == *(dev_t *)v2;
707 static guint
708 device_hash (gconstpointer v)
710 return (guint) *(dev_t *)v;
713 static void
714 get_mount_info (GFileInfo *fs_info,
715 const char *path,
716 GFileAttributeMatcher *matcher)
718 GStatBuf buf;
719 gboolean got_info;
720 gpointer info_as_ptr;
721 guint mount_info;
722 char *mountpoint;
723 dev_t *dev;
724 GUnixMountEntry *mount;
725 guint64 cache_time;
727 if (g_lstat (path, &buf) != 0)
728 return;
730 G_LOCK (mount_info_hash);
732 if (mount_info_hash == NULL)
733 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
734 g_free, NULL);
737 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
738 g_hash_table_remove_all (mount_info_hash);
740 got_info = g_hash_table_lookup_extended (mount_info_hash,
741 &buf.st_dev,
742 NULL,
743 &info_as_ptr);
745 G_UNLOCK (mount_info_hash);
747 mount_info = GPOINTER_TO_UINT (info_as_ptr);
749 if (!got_info)
751 mount_info = 0;
753 mountpoint = find_mountpoint_for (path, buf.st_dev);
754 if (mountpoint == NULL)
755 mountpoint = g_strdup ("/");
757 mount = g_unix_mount_at (mountpoint, &cache_time);
758 if (mount)
760 if (g_unix_mount_is_readonly (mount))
761 mount_info |= MOUNT_INFO_READONLY;
763 g_unix_mount_free (mount);
766 g_free (mountpoint);
768 dev = g_new0 (dev_t, 1);
769 *dev = buf.st_dev;
771 G_LOCK (mount_info_hash);
772 mount_info_hash_cache_time = cache_time;
773 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
774 G_UNLOCK (mount_info_hash);
777 if (mount_info & MOUNT_INFO_READONLY)
778 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
781 #endif
783 #ifdef G_OS_WIN32
785 static gboolean
786 is_xp_or_later (void)
788 static int result = -1;
790 if (result == -1)
792 #ifndef _MSC_VER
793 OSVERSIONINFOEX ver_info = {0};
794 DWORDLONG cond_mask = 0;
795 int op = VER_GREATER_EQUAL;
797 ver_info.dwOSVersionInfoSize = sizeof ver_info;
798 ver_info.dwMajorVersion = 5;
799 ver_info.dwMinorVersion = 1;
801 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
802 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
804 result = VerifyVersionInfo (&ver_info,
805 VER_MAJORVERSION | VER_MINORVERSION,
806 cond_mask) != 0;
807 #else
808 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
809 #endif
812 return result;
815 static wchar_t *
816 get_volume_for_path (const char *path)
818 long len;
819 wchar_t *wpath;
820 wchar_t *result;
822 wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
823 result = g_new (wchar_t, MAX_PATH);
825 if (!GetVolumePathNameW (wpath, result, MAX_PATH))
827 char *msg = g_win32_error_message (GetLastError ());
828 g_critical ("GetVolumePathName failed: %s", msg);
829 g_free (msg);
830 g_free (result);
831 g_free (wpath);
832 return NULL;
835 len = wcslen (result);
836 if (len > 0 && result[len-1] != L'\\')
838 result = g_renew (wchar_t, result, len + 2);
839 result[len] = L'\\';
840 result[len + 1] = 0;
843 g_free (wpath);
844 return result;
847 static char *
848 find_mountpoint_for (const char *file, dev_t dev)
850 wchar_t *wpath;
851 char *utf8_path;
853 wpath = get_volume_for_path (file);
854 if (!wpath)
855 return NULL;
857 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
859 g_free (wpath);
860 return utf8_path;
863 static void
864 get_filesystem_readonly (GFileInfo *info,
865 const char *path)
867 wchar_t *rootdir;
869 rootdir = get_volume_for_path (path);
871 if (rootdir)
873 if (is_xp_or_later ())
875 DWORD flags;
876 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
877 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
878 (flags & FILE_READ_ONLY_VOLUME) != 0);
880 else
882 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
883 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
887 g_free (rootdir);
890 #endif /* G_OS_WIN32 */
892 static GFileInfo *
893 g_local_file_query_filesystem_info (GFile *file,
894 const char *attributes,
895 GCancellable *cancellable,
896 GError **error)
898 GLocalFile *local = G_LOCAL_FILE (file);
899 GFileInfo *info;
900 int statfs_result = 0;
901 gboolean no_size;
902 #ifndef G_OS_WIN32
903 const char *fstype;
904 #ifdef USE_STATFS
905 guint64 block_size;
906 struct statfs statfs_buffer;
907 #elif defined(USE_STATVFS)
908 guint64 block_size;
909 struct statvfs statfs_buffer;
910 #endif /* USE_STATFS */
911 #endif /* G_OS_WIN32 */
912 GFileAttributeMatcher *attribute_matcher;
914 no_size = FALSE;
916 #ifdef USE_STATFS
918 #if STATFS_ARGS == 2
919 statfs_result = statfs (local->filename, &statfs_buffer);
920 #elif STATFS_ARGS == 4
921 statfs_result = statfs (local->filename, &statfs_buffer,
922 sizeof (statfs_buffer), 0);
923 #endif /* STATFS_ARGS == 2 */
924 block_size = statfs_buffer.f_bsize;
926 /* Many backends can't report free size (for instance the gvfs fuse
927 backend for backend not supporting this), and set f_bfree to 0,
928 but it can be 0 for real too. We treat the available == 0 and
929 free == 0 case as "both of these are invalid".
931 #ifndef G_OS_WIN32
932 if (statfs_result == 0 &&
933 statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
934 no_size = TRUE;
935 #endif /* G_OS_WIN32 */
937 #elif defined(USE_STATVFS)
938 statfs_result = statvfs (local->filename, &statfs_buffer);
939 block_size = statfs_buffer.f_frsize;
940 #endif /* USE_STATFS */
942 if (statfs_result == -1)
944 int errsv = errno;
946 g_set_error (error, G_IO_ERROR,
947 g_io_error_from_errno (errsv),
948 _("Error getting filesystem info: %s"),
949 g_strerror (errsv));
950 return NULL;
953 info = g_file_info_new ();
955 attribute_matcher = g_file_attribute_matcher_new (attributes);
957 if (!no_size &&
958 g_file_attribute_matcher_matches (attribute_matcher,
959 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
961 #ifdef G_OS_WIN32
962 gchar *localdir = g_path_get_dirname (local->filename);
963 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
964 ULARGE_INTEGER li;
966 g_free (localdir);
967 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
968 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
969 g_free (wdirname);
970 #else
971 #if defined(USE_STATFS) || defined(USE_STATVFS)
972 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
973 #endif
974 #endif
976 if (!no_size &&
977 g_file_attribute_matcher_matches (attribute_matcher,
978 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
980 #ifdef G_OS_WIN32
981 gchar *localdir = g_path_get_dirname (local->filename);
982 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
983 ULARGE_INTEGER li;
985 g_free (localdir);
986 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
987 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
988 g_free (wdirname);
989 #else
990 #if defined(USE_STATFS) || defined(USE_STATVFS)
991 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
992 #endif
993 #endif /* G_OS_WIN32 */
996 if (!no_size &&
997 g_file_attribute_matcher_matches (attribute_matcher,
998 G_FILE_ATTRIBUTE_FILESYSTEM_USED))
1000 #ifdef G_OS_WIN32
1001 gchar *localdir = g_path_get_dirname (local->filename);
1002 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1003 ULARGE_INTEGER li_free;
1004 ULARGE_INTEGER li_total;
1006 g_free (localdir);
1007 if (GetDiskFreeSpaceExW (wdirname, &li_free, &li_total, NULL))
1008 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, (guint64)li_total.QuadPart - (guint64)li_free.QuadPart);
1009 g_free (wdirname);
1010 #else
1011 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USED, block_size * (statfs_buffer.f_blocks - statfs_buffer.f_bfree));
1012 #endif /* G_OS_WIN32 */
1015 #ifndef G_OS_WIN32
1016 #ifdef USE_STATFS
1017 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1018 fstype = g_strdup (statfs_buffer.f_fstypename);
1019 #else
1020 fstype = get_fs_type (statfs_buffer.f_type);
1021 #endif
1023 #elif defined(USE_STATVFS)
1024 #if defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME)
1025 fstype = g_strdup (statfs_buffer.f_fstypename);
1026 #elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1027 fstype = g_strdup (statfs_buffer.f_basetype);
1028 #else
1029 fstype = NULL;
1030 #endif
1031 #endif /* USE_STATFS */
1033 if (fstype &&
1034 g_file_attribute_matcher_matches (attribute_matcher,
1035 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1036 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1037 #endif /* G_OS_WIN32 */
1039 if (g_file_attribute_matcher_matches (attribute_matcher,
1040 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1042 #ifdef G_OS_WIN32
1043 get_filesystem_readonly (info, local->filename);
1044 #else
1045 get_mount_info (info, local->filename, attribute_matcher);
1046 #endif /* G_OS_WIN32 */
1049 g_file_attribute_matcher_unref (attribute_matcher);
1051 return info;
1054 static GMount *
1055 g_local_file_find_enclosing_mount (GFile *file,
1056 GCancellable *cancellable,
1057 GError **error)
1059 GLocalFile *local = G_LOCAL_FILE (file);
1060 GStatBuf buf;
1061 char *mountpoint;
1062 GMount *mount;
1064 if (g_lstat (local->filename, &buf) != 0)
1066 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1067 /* Translators: This is an error message when trying to
1068 * find the enclosing (user visible) mount of a file, but
1069 * none exists. */
1070 _("Containing mount does not exist"));
1071 return NULL;
1074 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1075 if (mountpoint == NULL)
1077 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1078 /* Translators: This is an error message when trying to
1079 * find the enclosing (user visible) mount of a file, but
1080 * none exists. */
1081 _("Containing mount does not exist"));
1082 return NULL;
1085 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1086 g_free (mountpoint);
1087 if (mount)
1088 return mount;
1090 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1091 /* Translators: This is an error message when trying to find
1092 * the enclosing (user visible) mount of a file, but none
1093 * exists. */
1094 _("Containing mount does not exist"));
1095 return NULL;
1098 static GFile *
1099 g_local_file_set_display_name (GFile *file,
1100 const char *display_name,
1101 GCancellable *cancellable,
1102 GError **error)
1104 GLocalFile *local, *new_local;
1105 GFile *new_file, *parent;
1106 GStatBuf statbuf;
1107 GVfsClass *class;
1108 GVfs *vfs;
1109 int errsv;
1111 parent = g_file_get_parent (file);
1112 if (parent == NULL)
1114 g_set_error_literal (error, G_IO_ERROR,
1115 G_IO_ERROR_FAILED,
1116 _("Can't rename root directory"));
1117 return NULL;
1120 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1121 g_object_unref (parent);
1123 if (new_file == NULL)
1124 return NULL;
1125 local = G_LOCAL_FILE (file);
1126 new_local = G_LOCAL_FILE (new_file);
1128 if (g_lstat (new_local->filename, &statbuf) == -1)
1130 errsv = errno;
1132 if (errsv != ENOENT)
1134 g_set_error (error, G_IO_ERROR,
1135 g_io_error_from_errno (errsv),
1136 _("Error renaming file: %s"),
1137 g_strerror (errsv));
1138 return NULL;
1141 else
1143 g_set_error_literal (error, G_IO_ERROR,
1144 G_IO_ERROR_EXISTS,
1145 _("Can't rename file, filename already exists"));
1146 return NULL;
1149 if (g_rename (local->filename, new_local->filename) == -1)
1151 errsv = errno;
1153 if (errsv == EINVAL)
1154 /* We can't get a rename file into itself error herer,
1155 so this must be an invalid filename, on e.g. FAT */
1156 g_set_error_literal (error, G_IO_ERROR,
1157 G_IO_ERROR_INVALID_FILENAME,
1158 _("Invalid filename"));
1159 else
1160 g_set_error (error, G_IO_ERROR,
1161 g_io_error_from_errno (errsv),
1162 _("Error renaming file: %s"),
1163 g_strerror (errsv));
1164 g_object_unref (new_file);
1165 return NULL;
1168 vfs = g_vfs_get_default ();
1169 class = G_VFS_GET_CLASS (vfs);
1170 if (class->local_file_moved)
1171 class->local_file_moved (vfs, local->filename, new_local->filename);
1173 return new_file;
1176 static GFileInfo *
1177 g_local_file_query_info (GFile *file,
1178 const char *attributes,
1179 GFileQueryInfoFlags flags,
1180 GCancellable *cancellable,
1181 GError **error)
1183 GLocalFile *local = G_LOCAL_FILE (file);
1184 GFileInfo *info;
1185 GFileAttributeMatcher *matcher;
1186 char *basename, *dirname;
1187 GLocalParentFileInfo parent_info;
1189 matcher = g_file_attribute_matcher_new (attributes);
1191 basename = g_path_get_basename (local->filename);
1193 dirname = g_path_get_dirname (local->filename);
1194 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1195 g_free (dirname);
1197 info = _g_local_file_info_get (basename, local->filename,
1198 matcher, flags, &parent_info,
1199 error);
1202 _g_local_file_info_free_parent_info (&parent_info);
1203 g_free (basename);
1205 g_file_attribute_matcher_unref (matcher);
1207 return info;
1210 static GFileAttributeInfoList *
1211 g_local_file_query_settable_attributes (GFile *file,
1212 GCancellable *cancellable,
1213 GError **error)
1215 return g_file_attribute_info_list_ref (local_writable_attributes);
1218 static GFileAttributeInfoList *
1219 g_local_file_query_writable_namespaces (GFile *file,
1220 GCancellable *cancellable,
1221 GError **error)
1223 GFileAttributeInfoList *list;
1224 GVfsClass *class;
1225 GVfs *vfs;
1227 if (g_once_init_enter (&local_writable_namespaces))
1229 /* Writable namespaces: */
1231 list = g_file_attribute_info_list_new ();
1233 #ifdef HAVE_XATTR
1234 g_file_attribute_info_list_add (list,
1235 "xattr",
1236 G_FILE_ATTRIBUTE_TYPE_STRING,
1237 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
1238 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1239 g_file_attribute_info_list_add (list,
1240 "xattr-sys",
1241 G_FILE_ATTRIBUTE_TYPE_STRING,
1242 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
1243 #endif
1245 vfs = g_vfs_get_default ();
1246 class = G_VFS_GET_CLASS (vfs);
1247 if (class->add_writable_namespaces)
1248 class->add_writable_namespaces (vfs, list);
1250 g_once_init_leave (&local_writable_namespaces, (gsize)list);
1252 list = (GFileAttributeInfoList *)local_writable_namespaces;
1254 return g_file_attribute_info_list_ref (list);
1257 static gboolean
1258 g_local_file_set_attribute (GFile *file,
1259 const char *attribute,
1260 GFileAttributeType type,
1261 gpointer value_p,
1262 GFileQueryInfoFlags flags,
1263 GCancellable *cancellable,
1264 GError **error)
1266 GLocalFile *local = G_LOCAL_FILE (file);
1268 return _g_local_file_info_set_attribute (local->filename,
1269 attribute,
1270 type,
1271 value_p,
1272 flags,
1273 cancellable,
1274 error);
1277 static gboolean
1278 g_local_file_set_attributes_from_info (GFile *file,
1279 GFileInfo *info,
1280 GFileQueryInfoFlags flags,
1281 GCancellable *cancellable,
1282 GError **error)
1284 GLocalFile *local = G_LOCAL_FILE (file);
1285 int res, chained_res;
1286 GFileIface *default_iface;
1288 res = _g_local_file_info_set_attributes (local->filename,
1289 info, flags,
1290 cancellable,
1291 error);
1293 if (!res)
1294 error = NULL; /* Don't write over error if further errors */
1296 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1298 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1300 return res && chained_res;
1303 static GFileInputStream *
1304 g_local_file_read (GFile *file,
1305 GCancellable *cancellable,
1306 GError **error)
1308 GLocalFile *local = G_LOCAL_FILE (file);
1309 int fd, ret;
1310 GLocalFileStat buf;
1312 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1313 if (fd == -1)
1315 int errsv = errno;
1317 #ifdef G_OS_WIN32
1318 if (errsv == EACCES)
1320 ret = _stati64 (local->filename, &buf);
1321 if (ret == 0 && S_ISDIR (buf.st_mode))
1323 g_set_error_literal (error, G_IO_ERROR,
1324 G_IO_ERROR_IS_DIRECTORY,
1325 _("Can't open directory"));
1326 return NULL;
1329 #endif
1331 g_set_error (error, G_IO_ERROR,
1332 g_io_error_from_errno (errsv),
1333 _("Error opening file: %s"),
1334 g_strerror (errsv));
1335 return NULL;
1338 #ifdef G_OS_WIN32
1339 ret = _fstati64 (fd, &buf);
1340 #else
1341 ret = fstat (fd, &buf);
1342 #endif
1344 if (ret == 0 && S_ISDIR (buf.st_mode))
1346 close (fd);
1347 g_set_error_literal (error, G_IO_ERROR,
1348 G_IO_ERROR_IS_DIRECTORY,
1349 _("Can't open directory"));
1350 return NULL;
1353 return _g_local_file_input_stream_new (fd);
1356 static GFileOutputStream *
1357 g_local_file_append_to (GFile *file,
1358 GFileCreateFlags flags,
1359 GCancellable *cancellable,
1360 GError **error)
1362 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1363 flags, cancellable, error);
1366 static GFileOutputStream *
1367 g_local_file_create (GFile *file,
1368 GFileCreateFlags flags,
1369 GCancellable *cancellable,
1370 GError **error)
1372 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1373 FALSE,
1374 flags, cancellable, error);
1377 static GFileOutputStream *
1378 g_local_file_replace (GFile *file,
1379 const char *etag,
1380 gboolean make_backup,
1381 GFileCreateFlags flags,
1382 GCancellable *cancellable,
1383 GError **error)
1385 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1386 FALSE,
1387 etag, make_backup, flags,
1388 cancellable, error);
1391 static GFileIOStream *
1392 g_local_file_open_readwrite (GFile *file,
1393 GCancellable *cancellable,
1394 GError **error)
1396 GFileOutputStream *output;
1397 GFileIOStream *res;
1399 output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
1400 TRUE,
1401 cancellable, error);
1402 if (output == NULL)
1403 return NULL;
1405 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1406 g_object_unref (output);
1407 return res;
1410 static GFileIOStream *
1411 g_local_file_create_readwrite (GFile *file,
1412 GFileCreateFlags flags,
1413 GCancellable *cancellable,
1414 GError **error)
1416 GFileOutputStream *output;
1417 GFileIOStream *res;
1419 output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1420 TRUE, flags,
1421 cancellable, error);
1422 if (output == NULL)
1423 return NULL;
1425 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1426 g_object_unref (output);
1427 return res;
1430 static GFileIOStream *
1431 g_local_file_replace_readwrite (GFile *file,
1432 const char *etag,
1433 gboolean make_backup,
1434 GFileCreateFlags flags,
1435 GCancellable *cancellable,
1436 GError **error)
1438 GFileOutputStream *output;
1439 GFileIOStream *res;
1441 output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1442 TRUE,
1443 etag, make_backup, flags,
1444 cancellable, error);
1445 if (output == NULL)
1446 return NULL;
1448 res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
1449 g_object_unref (output);
1450 return res;
1453 static gboolean
1454 g_local_file_delete (GFile *file,
1455 GCancellable *cancellable,
1456 GError **error)
1458 GLocalFile *local = G_LOCAL_FILE (file);
1459 GVfsClass *class;
1460 GVfs *vfs;
1462 if (g_remove (local->filename) == -1)
1464 int errsv = errno;
1466 /* Posix allows EEXIST too, but the more sane error
1467 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1468 expects */
1469 if (errsv == EEXIST)
1470 errsv = ENOTEMPTY;
1472 g_set_error (error, G_IO_ERROR,
1473 g_io_error_from_errno (errsv),
1474 _("Error removing file: %s"),
1475 g_strerror (errsv));
1476 return FALSE;
1479 vfs = g_vfs_get_default ();
1480 class = G_VFS_GET_CLASS (vfs);
1481 if (class->local_file_removed)
1482 class->local_file_removed (vfs, local->filename);
1484 return TRUE;
1487 #ifndef G_OS_WIN32
1489 static char *
1490 strip_trailing_slashes (const char *path)
1492 char *path_copy;
1493 int len;
1495 path_copy = g_strdup (path);
1496 len = strlen (path_copy);
1497 while (len > 1 && path_copy[len-1] == '/')
1498 path_copy[--len] = 0;
1500 return path_copy;
1503 static char *
1504 expand_symlink (const char *link)
1506 char *resolved, *canonical, *parent, *link2;
1507 char symlink_value[4096];
1508 #ifdef G_OS_WIN32
1509 #else
1510 ssize_t res;
1511 #endif
1513 #ifdef G_OS_WIN32
1514 #else
1515 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1517 if (res == -1)
1518 return g_strdup (link);
1519 symlink_value[res] = 0;
1520 #endif
1522 if (g_path_is_absolute (symlink_value))
1523 return canonicalize_filename (symlink_value);
1524 else
1526 link2 = strip_trailing_slashes (link);
1527 parent = g_path_get_dirname (link2);
1528 g_free (link2);
1530 resolved = g_build_filename (parent, symlink_value, NULL);
1531 g_free (parent);
1533 canonical = canonicalize_filename (resolved);
1535 g_free (resolved);
1537 return canonical;
1541 static char *
1542 get_parent (const char *path,
1543 dev_t *parent_dev)
1545 char *parent, *tmp;
1546 GStatBuf parent_stat;
1547 int num_recursions;
1548 char *path_copy;
1550 path_copy = strip_trailing_slashes (path);
1552 parent = g_path_get_dirname (path_copy);
1553 if (strcmp (parent, ".") == 0 ||
1554 strcmp (parent, path_copy) == 0)
1556 g_free (parent);
1557 g_free (path_copy);
1558 return NULL;
1560 g_free (path_copy);
1562 num_recursions = 0;
1563 do {
1564 if (g_lstat (parent, &parent_stat) != 0)
1566 g_free (parent);
1567 return NULL;
1570 if (S_ISLNK (parent_stat.st_mode))
1572 tmp = parent;
1573 parent = expand_symlink (parent);
1574 g_free (tmp);
1577 num_recursions++;
1578 if (num_recursions > 12)
1580 g_free (parent);
1581 return NULL;
1583 } while (S_ISLNK (parent_stat.st_mode));
1585 *parent_dev = parent_stat.st_dev;
1587 return parent;
1590 static char *
1591 expand_all_symlinks (const char *path)
1593 char *parent, *parent_expanded;
1594 char *basename, *res;
1595 dev_t parent_dev;
1597 parent = get_parent (path, &parent_dev);
1598 if (parent)
1600 parent_expanded = expand_all_symlinks (parent);
1601 g_free (parent);
1602 basename = g_path_get_basename (path);
1603 res = g_build_filename (parent_expanded, basename, NULL);
1604 g_free (basename);
1605 g_free (parent_expanded);
1607 else
1608 res = g_strdup (path);
1610 return res;
1613 static char *
1614 find_mountpoint_for (const char *file,
1615 dev_t dev)
1617 char *dir, *parent;
1618 dev_t dir_dev, parent_dev;
1620 dir = g_strdup (file);
1621 dir_dev = dev;
1623 while (1)
1625 parent = get_parent (dir, &parent_dev);
1626 if (parent == NULL)
1627 return dir;
1629 if (parent_dev != dir_dev)
1631 g_free (parent);
1632 return dir;
1635 g_free (dir);
1636 dir = parent;
1640 static char *
1641 find_topdir_for (const char *file)
1643 char *dir;
1644 dev_t dir_dev;
1646 dir = get_parent (file, &dir_dev);
1647 if (dir == NULL)
1648 return NULL;
1650 return find_mountpoint_for (dir, dir_dev);
1653 static char *
1654 get_unique_filename (const char *basename,
1655 int id)
1657 const char *dot;
1659 if (id == 1)
1660 return g_strdup (basename);
1662 dot = strchr (basename, '.');
1663 if (dot)
1664 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1665 else
1666 return g_strdup_printf ("%s.%d", basename, id);
1669 static gboolean
1670 path_has_prefix (const char *path,
1671 const char *prefix)
1673 int prefix_len;
1675 if (prefix == NULL)
1676 return TRUE;
1678 prefix_len = strlen (prefix);
1680 if (strncmp (path, prefix, prefix_len) == 0 &&
1681 (prefix_len == 0 || /* empty prefix always matches */
1682 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1683 path[prefix_len] == 0 ||
1684 path[prefix_len] == '/'))
1685 return TRUE;
1687 return FALSE;
1690 static char *
1691 try_make_relative (const char *path,
1692 const char *base)
1694 char *path2, *base2;
1695 char *relative;
1697 path2 = expand_all_symlinks (path);
1698 base2 = expand_all_symlinks (base);
1700 relative = NULL;
1701 if (path_has_prefix (path2, base2))
1703 relative = path2 + strlen (base2);
1704 while (*relative == '/')
1705 relative ++;
1706 relative = g_strdup (relative);
1708 g_free (path2);
1709 g_free (base2);
1711 if (relative)
1712 return relative;
1714 /* Failed, use abs path */
1715 return g_strdup (path);
1718 static char *
1719 escape_trash_name (char *name)
1721 GString *str;
1722 const gchar hex[16] = "0123456789ABCDEF";
1724 str = g_string_new ("");
1726 while (*name != 0)
1728 char c;
1730 c = *name++;
1732 if (g_ascii_isprint (c))
1733 g_string_append_c (str, c);
1734 else
1736 g_string_append_c (str, '%');
1737 g_string_append_c (str, hex[((guchar)c) >> 4]);
1738 g_string_append_c (str, hex[((guchar)c) & 0xf]);
1742 return g_string_free (str, FALSE);
1745 gboolean
1746 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1748 static gsize home_dev_set = 0;
1749 static dev_t home_dev;
1750 char *topdir, *globaldir, *trashdir, *tmpname;
1751 uid_t uid;
1752 char uid_str[32];
1753 GStatBuf global_stat, trash_stat;
1754 gboolean res;
1756 if (g_once_init_enter (&home_dev_set))
1758 GStatBuf home_stat;
1760 g_stat (g_get_home_dir (), &home_stat);
1761 home_dev = home_stat.st_dev;
1762 g_once_init_leave (&home_dev_set, 1);
1765 /* Assume we can trash to the home */
1766 if (dir_dev == home_dev)
1767 return TRUE;
1769 topdir = find_mountpoint_for (dirname, dir_dev);
1770 if (topdir == NULL)
1771 return FALSE;
1773 globaldir = g_build_filename (topdir, ".Trash", NULL);
1774 if (g_lstat (globaldir, &global_stat) == 0 &&
1775 S_ISDIR (global_stat.st_mode) &&
1776 (global_stat.st_mode & S_ISVTX) != 0)
1778 /* got a toplevel sysadmin created dir, assume we
1779 * can trash to it (we should be able to create a dir)
1780 * This fails for the FAT case where the ownership of
1781 * that dir would be wrong though..
1783 g_free (globaldir);
1784 g_free (topdir);
1785 return TRUE;
1787 g_free (globaldir);
1789 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1790 uid = geteuid ();
1791 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1793 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1794 trashdir = g_build_filename (topdir, tmpname, NULL);
1795 g_free (tmpname);
1797 if (g_lstat (trashdir, &trash_stat) == 0)
1799 g_free (topdir);
1800 g_free (trashdir);
1801 return S_ISDIR (trash_stat.st_mode) &&
1802 trash_stat.st_uid == uid;
1804 g_free (trashdir);
1806 /* User specific trash didn't exist, can we create it? */
1807 res = g_access (topdir, W_OK) == 0;
1808 g_free (topdir);
1810 return res;
1814 static gboolean
1815 g_local_file_trash (GFile *file,
1816 GCancellable *cancellable,
1817 GError **error)
1819 GLocalFile *local = G_LOCAL_FILE (file);
1820 GStatBuf file_stat, home_stat;
1821 const char *homedir;
1822 char *trashdir, *topdir, *infodir, *filesdir;
1823 char *basename, *trashname, *trashfile, *infoname, *infofile;
1824 char *original_name, *original_name_escaped;
1825 int i;
1826 char *data;
1827 gboolean is_homedir_trash;
1828 char delete_time[32];
1829 int fd;
1830 GStatBuf trash_stat, global_stat;
1831 char *dirname, *globaldir;
1832 GVfsClass *class;
1833 GVfs *vfs;
1835 if (g_lstat (local->filename, &file_stat) != 0)
1837 int errsv = errno;
1839 g_set_error (error, G_IO_ERROR,
1840 g_io_error_from_errno (errsv),
1841 _("Error trashing file: %s"),
1842 g_strerror (errsv));
1843 return FALSE;
1846 homedir = g_get_home_dir ();
1847 g_stat (homedir, &home_stat);
1849 is_homedir_trash = FALSE;
1850 trashdir = NULL;
1851 if (file_stat.st_dev == home_stat.st_dev)
1853 is_homedir_trash = TRUE;
1854 errno = 0;
1855 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1856 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1858 char *display_name;
1859 int errsv = errno;
1861 display_name = g_filename_display_name (trashdir);
1862 g_set_error (error, G_IO_ERROR,
1863 g_io_error_from_errno (errsv),
1864 _("Unable to create trash dir %s: %s"),
1865 display_name, g_strerror (errsv));
1866 g_free (display_name);
1867 g_free (trashdir);
1868 return FALSE;
1870 topdir = g_strdup (g_get_user_data_dir ());
1872 else
1874 uid_t uid;
1875 char uid_str[32];
1877 uid = geteuid ();
1878 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1880 topdir = find_topdir_for (local->filename);
1881 if (topdir == NULL)
1883 g_set_error_literal (error, G_IO_ERROR,
1884 G_IO_ERROR_NOT_SUPPORTED,
1885 _("Unable to find toplevel directory for trash"));
1886 return FALSE;
1889 /* Try looking for global trash dir $topdir/.Trash/$uid */
1890 globaldir = g_build_filename (topdir, ".Trash", NULL);
1891 if (g_lstat (globaldir, &global_stat) == 0 &&
1892 S_ISDIR (global_stat.st_mode) &&
1893 (global_stat.st_mode & S_ISVTX) != 0)
1895 trashdir = g_build_filename (globaldir, uid_str, NULL);
1897 if (g_lstat (trashdir, &trash_stat) == 0)
1899 if (!S_ISDIR (trash_stat.st_mode) ||
1900 trash_stat.st_uid != uid)
1902 /* Not a directory or not owned by user, ignore */
1903 g_free (trashdir);
1904 trashdir = NULL;
1907 else if (g_mkdir (trashdir, 0700) == -1)
1909 g_free (trashdir);
1910 trashdir = NULL;
1913 g_free (globaldir);
1915 if (trashdir == NULL)
1917 gboolean tried_create;
1919 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1920 dirname = g_strdup_printf (".Trash-%s", uid_str);
1921 trashdir = g_build_filename (topdir, dirname, NULL);
1922 g_free (dirname);
1924 tried_create = FALSE;
1926 retry:
1927 if (g_lstat (trashdir, &trash_stat) == 0)
1929 if (!S_ISDIR (trash_stat.st_mode) ||
1930 trash_stat.st_uid != uid)
1932 /* Remove the failed directory */
1933 if (tried_create)
1934 g_remove (trashdir);
1936 /* Not a directory or not owned by user, ignore */
1937 g_free (trashdir);
1938 trashdir = NULL;
1941 else
1943 if (!tried_create &&
1944 g_mkdir (trashdir, 0700) != -1)
1946 /* Ensure that the created dir has the right uid etc.
1947 This might fail on e.g. a FAT dir */
1948 tried_create = TRUE;
1949 goto retry;
1951 else
1953 g_free (trashdir);
1954 trashdir = NULL;
1959 if (trashdir == NULL)
1961 g_free (topdir);
1962 g_set_error_literal (error, G_IO_ERROR,
1963 G_IO_ERROR_NOT_SUPPORTED,
1964 _("Unable to find or create trash directory"));
1965 return FALSE;
1969 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1971 infodir = g_build_filename (trashdir, "info", NULL);
1972 filesdir = g_build_filename (trashdir, "files", NULL);
1973 g_free (trashdir);
1975 /* Make sure we have the subdirectories */
1976 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1977 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1979 g_free (topdir);
1980 g_free (infodir);
1981 g_free (filesdir);
1982 g_set_error_literal (error, G_IO_ERROR,
1983 G_IO_ERROR_NOT_SUPPORTED,
1984 _("Unable to find or create trash directory"));
1985 return FALSE;
1988 basename = g_path_get_basename (local->filename);
1989 i = 1;
1990 trashname = NULL;
1991 infofile = NULL;
1992 do {
1993 g_free (trashname);
1994 g_free (infofile);
1996 trashname = get_unique_filename (basename, i++);
1997 infoname = g_strconcat (trashname, ".trashinfo", NULL);
1998 infofile = g_build_filename (infodir, infoname, NULL);
1999 g_free (infoname);
2001 fd = open (infofile, O_CREAT | O_EXCL, 0666);
2002 } while (fd == -1 && errno == EEXIST);
2004 g_free (basename);
2005 g_free (infodir);
2007 if (fd == -1)
2009 int errsv = errno;
2011 g_free (filesdir);
2012 g_free (topdir);
2013 g_free (trashname);
2014 g_free (infofile);
2016 g_set_error (error, G_IO_ERROR,
2017 g_io_error_from_errno (errsv),
2018 _("Unable to create trashing info file: %s"),
2019 g_strerror (errsv));
2020 return FALSE;
2023 close (fd);
2025 /* TODO: Maybe we should verify that you can delete the file from the trash
2026 before moving it? OTOH, that is hard, as it needs a recursive scan */
2028 trashfile = g_build_filename (filesdir, trashname, NULL);
2030 g_free (filesdir);
2032 if (g_rename (local->filename, trashfile) == -1)
2034 int errsv = errno;
2036 g_free (topdir);
2037 g_free (trashname);
2038 g_free (infofile);
2039 g_free (trashfile);
2041 if (errsv == EXDEV)
2042 /* The trash dir was actually on another fs anyway!?
2043 This can happen when the same device is mounted multiple
2044 times, or with bind mounts of the same fs. */
2045 g_set_error (error, G_IO_ERROR,
2046 G_IO_ERROR_NOT_SUPPORTED,
2047 _("Unable to trash file: %s"),
2048 g_strerror (errsv));
2049 else
2050 g_set_error (error, G_IO_ERROR,
2051 g_io_error_from_errno (errsv),
2052 _("Unable to trash file: %s"),
2053 g_strerror (errsv));
2054 return FALSE;
2057 vfs = g_vfs_get_default ();
2058 class = G_VFS_GET_CLASS (vfs);
2059 if (class->local_file_moved)
2060 class->local_file_moved (vfs, local->filename, trashfile);
2062 g_free (trashfile);
2064 /* TODO: Do we need to update mtime/atime here after the move? */
2066 /* Use absolute names for homedir */
2067 if (is_homedir_trash)
2068 original_name = g_strdup (local->filename);
2069 else
2070 original_name = try_make_relative (local->filename, topdir);
2071 original_name_escaped = escape_trash_name (original_name);
2073 g_free (original_name);
2074 g_free (topdir);
2077 time_t t;
2078 struct tm now;
2079 t = time (NULL);
2080 localtime_r (&t, &now);
2081 delete_time[0] = 0;
2082 strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
2085 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
2086 original_name_escaped, delete_time);
2088 g_file_set_contents (infofile, data, -1, NULL);
2089 g_free (infofile);
2090 g_free (data);
2092 g_free (original_name_escaped);
2093 g_free (trashname);
2095 return TRUE;
2097 #else /* G_OS_WIN32 */
2098 gboolean
2099 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
2101 return FALSE; /* XXX ??? */
2104 static gboolean
2105 g_local_file_trash (GFile *file,
2106 GCancellable *cancellable,
2107 GError **error)
2109 GLocalFile *local = G_LOCAL_FILE (file);
2110 SHFILEOPSTRUCTW op = {0};
2111 gboolean success;
2112 wchar_t *wfilename;
2113 long len;
2115 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
2116 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
2117 wfilename = g_renew (wchar_t, wfilename, len + 2);
2118 wfilename[len + 1] = 0;
2120 op.wFunc = FO_DELETE;
2121 op.pFrom = wfilename;
2122 op.fFlags = FOF_ALLOWUNDO;
2124 success = SHFileOperationW (&op) == 0;
2126 if (success && op.fAnyOperationsAborted)
2128 if (cancellable && !g_cancellable_is_cancelled (cancellable))
2129 g_cancellable_cancel (cancellable);
2130 g_set_error (error, G_IO_ERROR,
2131 G_IO_ERROR_CANCELLED,
2132 _("Unable to trash file: %s"),
2133 _("Operation was cancelled"));
2134 success = FALSE;
2136 else if (!success)
2137 g_set_error (error, G_IO_ERROR,
2138 G_IO_ERROR_FAILED,
2139 _("Unable to trash file: %s"),
2140 _("internal error"));
2142 g_free (wfilename);
2143 return success;
2145 #endif /* G_OS_WIN32 */
2147 static gboolean
2148 g_local_file_make_directory (GFile *file,
2149 GCancellable *cancellable,
2150 GError **error)
2152 GLocalFile *local = G_LOCAL_FILE (file);
2154 if (g_mkdir (local->filename, 0777) == -1)
2156 int errsv = errno;
2158 if (errsv == EINVAL)
2159 /* This must be an invalid filename, on e.g. FAT */
2160 g_set_error_literal (error, G_IO_ERROR,
2161 G_IO_ERROR_INVALID_FILENAME,
2162 _("Invalid filename"));
2163 else
2164 g_set_error (error, G_IO_ERROR,
2165 g_io_error_from_errno (errsv),
2166 _("Error creating directory: %s"),
2167 g_strerror (errsv));
2168 return FALSE;
2171 return TRUE;
2174 static gboolean
2175 g_local_file_make_symbolic_link (GFile *file,
2176 const char *symlink_value,
2177 GCancellable *cancellable,
2178 GError **error)
2180 #ifdef HAVE_SYMLINK
2181 GLocalFile *local = G_LOCAL_FILE (file);
2183 if (symlink (symlink_value, local->filename) == -1)
2185 int errsv = errno;
2187 if (errsv == EINVAL)
2188 /* This must be an invalid filename, on e.g. FAT */
2189 g_set_error_literal (error, G_IO_ERROR,
2190 G_IO_ERROR_INVALID_FILENAME,
2191 _("Invalid filename"));
2192 else if (errsv == EPERM)
2193 g_set_error (error, G_IO_ERROR,
2194 G_IO_ERROR_NOT_SUPPORTED,
2195 _("Filesystem does not support symbolic links"));
2196 else
2197 g_set_error (error, G_IO_ERROR,
2198 g_io_error_from_errno (errsv),
2199 _("Error making symbolic link: %s"),
2200 g_strerror (errsv));
2201 return FALSE;
2203 return TRUE;
2204 #else
2205 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
2206 return FALSE;
2207 #endif
2211 static gboolean
2212 g_local_file_copy (GFile *source,
2213 GFile *destination,
2214 GFileCopyFlags flags,
2215 GCancellable *cancellable,
2216 GFileProgressCallback progress_callback,
2217 gpointer progress_callback_data,
2218 GError **error)
2220 /* Fall back to default copy */
2221 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2222 return FALSE;
2225 static gboolean
2226 g_local_file_move (GFile *source,
2227 GFile *destination,
2228 GFileCopyFlags flags,
2229 GCancellable *cancellable,
2230 GFileProgressCallback progress_callback,
2231 gpointer progress_callback_data,
2232 GError **error)
2234 GLocalFile *local_source, *local_destination;
2235 GStatBuf statbuf;
2236 gboolean destination_exist, source_is_dir;
2237 char *backup_name;
2238 int res;
2239 off_t source_size;
2240 GVfsClass *class;
2241 GVfs *vfs;
2243 if (!G_IS_LOCAL_FILE (source) ||
2244 !G_IS_LOCAL_FILE (destination))
2246 /* Fall back to default move */
2247 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2248 return FALSE;
2251 local_source = G_LOCAL_FILE (source);
2252 local_destination = G_LOCAL_FILE (destination);
2254 res = g_lstat (local_source->filename, &statbuf);
2255 if (res == -1)
2257 int errsv = errno;
2259 g_set_error (error, G_IO_ERROR,
2260 g_io_error_from_errno (errsv),
2261 _("Error moving file: %s"),
2262 g_strerror (errsv));
2263 return FALSE;
2266 source_is_dir = S_ISDIR (statbuf.st_mode);
2267 source_size = statbuf.st_size;
2269 destination_exist = FALSE;
2270 res = g_lstat (local_destination->filename, &statbuf);
2271 if (res == 0)
2273 destination_exist = TRUE; /* Target file exists */
2275 if (flags & G_FILE_COPY_OVERWRITE)
2277 /* Always fail on dirs, even with overwrite */
2278 if (S_ISDIR (statbuf.st_mode))
2280 if (source_is_dir)
2281 g_set_error_literal (error,
2282 G_IO_ERROR,
2283 G_IO_ERROR_WOULD_MERGE,
2284 _("Can't move directory over directory"));
2285 else
2286 g_set_error_literal (error,
2287 G_IO_ERROR,
2288 G_IO_ERROR_IS_DIRECTORY,
2289 _("Can't copy over directory"));
2290 return FALSE;
2293 else
2295 g_set_error_literal (error,
2296 G_IO_ERROR,
2297 G_IO_ERROR_EXISTS,
2298 _("Target file exists"));
2299 return FALSE;
2303 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2305 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2306 if (g_rename (local_destination->filename, backup_name) == -1)
2308 g_set_error_literal (error,
2309 G_IO_ERROR,
2310 G_IO_ERROR_CANT_CREATE_BACKUP,
2311 _("Backup file creation failed"));
2312 g_free (backup_name);
2313 return FALSE;
2315 g_free (backup_name);
2316 destination_exist = FALSE; /* It did, but no more */
2319 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2321 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2322 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2323 res = g_unlink (local_destination->filename);
2324 if (res == -1)
2326 int errsv = errno;
2328 g_set_error (error, G_IO_ERROR,
2329 g_io_error_from_errno (errsv),
2330 _("Error removing target file: %s"),
2331 g_strerror (errsv));
2332 return FALSE;
2336 if (g_rename (local_source->filename, local_destination->filename) == -1)
2338 int errsv = errno;
2340 if (errsv == EXDEV)
2341 /* This will cause the fallback code to run */
2342 g_set_error_literal (error, G_IO_ERROR,
2343 G_IO_ERROR_NOT_SUPPORTED,
2344 _("Move between mounts not supported"));
2345 else if (errsv == EINVAL)
2346 /* This must be an invalid filename, on e.g. FAT, or
2347 we're trying to move the file into itself...
2348 We return invalid filename for both... */
2349 g_set_error_literal (error, G_IO_ERROR,
2350 G_IO_ERROR_INVALID_FILENAME,
2351 _("Invalid filename"));
2352 else
2353 g_set_error (error, G_IO_ERROR,
2354 g_io_error_from_errno (errsv),
2355 _("Error moving file: %s"),
2356 g_strerror (errsv));
2357 return FALSE;
2360 vfs = g_vfs_get_default ();
2361 class = G_VFS_GET_CLASS (vfs);
2362 if (class->local_file_moved)
2363 class->local_file_moved (vfs, local_source->filename, local_destination->filename);
2365 /* Make sure we send full copied size */
2366 if (progress_callback)
2367 progress_callback (source_size, source_size, progress_callback_data);
2369 return TRUE;
2372 static GFileMonitor*
2373 g_local_file_monitor_dir (GFile *file,
2374 GFileMonitorFlags flags,
2375 GCancellable *cancellable,
2376 GError **error)
2378 GLocalFile* local_file = G_LOCAL_FILE(file);
2379 return _g_local_directory_monitor_new (local_file->filename, flags, error);
2382 static GFileMonitor*
2383 g_local_file_monitor_file (GFile *file,
2384 GFileMonitorFlags flags,
2385 GCancellable *cancellable,
2386 GError **error)
2388 GLocalFile* local_file = G_LOCAL_FILE(file);
2389 return _g_local_file_monitor_new (local_file->filename, flags, error);
2392 static void
2393 g_local_file_file_iface_init (GFileIface *iface)
2395 iface->dup = g_local_file_dup;
2396 iface->hash = g_local_file_hash;
2397 iface->equal = g_local_file_equal;
2398 iface->is_native = g_local_file_is_native;
2399 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2400 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2401 iface->get_basename = g_local_file_get_basename;
2402 iface->get_path = g_local_file_get_path;
2403 iface->get_uri = g_local_file_get_uri;
2404 iface->get_parse_name = g_local_file_get_parse_name;
2405 iface->get_parent = g_local_file_get_parent;
2406 iface->prefix_matches = g_local_file_prefix_matches;
2407 iface->get_relative_path = g_local_file_get_relative_path;
2408 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2409 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2410 iface->set_display_name = g_local_file_set_display_name;
2411 iface->enumerate_children = g_local_file_enumerate_children;
2412 iface->query_info = g_local_file_query_info;
2413 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2414 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2415 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2416 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2417 iface->set_attribute = g_local_file_set_attribute;
2418 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2419 iface->read_fn = g_local_file_read;
2420 iface->append_to = g_local_file_append_to;
2421 iface->create = g_local_file_create;
2422 iface->replace = g_local_file_replace;
2423 iface->open_readwrite = g_local_file_open_readwrite;
2424 iface->create_readwrite = g_local_file_create_readwrite;
2425 iface->replace_readwrite = g_local_file_replace_readwrite;
2426 iface->delete_file = g_local_file_delete;
2427 iface->trash = g_local_file_trash;
2428 iface->make_directory = g_local_file_make_directory;
2429 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2430 iface->copy = g_local_file_copy;
2431 iface->move = g_local_file_move;
2432 iface->monitor_dir = g_local_file_monitor_dir;
2433 iface->monitor_file = g_local_file_monitor_file;
2435 iface->supports_thread_contexts = TRUE;