Add a GIcon implementation that can add an emblem to another icon.
[glib.git] / gio / glocalfile.c
blob634a38a2156611943e5182edfc960da4b051fb94
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 #if defined(HAVE_STATFS) && defined(HAVE_STATVFS)
54 /* Some systems have both statfs and statvfs, pick the
55 most "native" for these */
56 # if !defined(HAVE_STRUCT_STATFS_F_BAVAIL)
57 /* on solaris and irix, statfs doesn't even have the
58 f_bavail field */
59 # define USE_STATVFS
60 # else
61 /* at least on linux, statfs is the actual syscall */
62 # define USE_STATFS
63 # endif
65 #elif defined(HAVE_STATFS)
67 # define USE_STATFS
69 #elif defined(HAVE_STATVFS)
71 # define USE_STATVFS
73 #endif
75 #include "gfileattribute.h"
76 #include "glocalfile.h"
77 #include "glocalfileinfo.h"
78 #include "glocalfileenumerator.h"
79 #include "glocalfileinputstream.h"
80 #include "glocalfileoutputstream.h"
81 #include "glocaldirectorymonitor.h"
82 #include "glocalfilemonitor.h"
83 #include "gmountprivate.h"
84 #include "gunixmounts.h"
85 #include "gioerror.h"
86 #include <glib/gstdio.h>
87 #include "glibintl.h"
89 #ifdef G_OS_WIN32
90 #define _WIN32_WINNT 0x0500
91 #include <windows.h>
92 #include <io.h>
93 #include <direct.h>
95 #ifndef FILE_READ_ONLY_VOLUME
96 #define FILE_READ_ONLY_VOLUME 0x00080000
97 #endif
99 #ifndef S_ISDIR
100 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
101 #endif
102 #ifndef S_ISLNK
103 #define S_ISLNK(m) (0)
104 #endif
105 #endif
107 #include "gioalias.h"
109 static void g_local_file_file_iface_init (GFileIface *iface);
111 static GFileAttributeInfoList *local_writable_attributes = NULL;
112 static GFileAttributeInfoList *local_writable_namespaces = NULL;
114 struct _GLocalFile
116 GObject parent_instance;
118 char *filename;
121 #define g_local_file_get_type _g_local_file_get_type
122 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
123 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
124 g_local_file_file_iface_init))
126 static char *find_mountpoint_for (const char *file, dev_t dev);
128 static void
129 g_local_file_finalize (GObject *object)
131 GLocalFile *local;
133 local = G_LOCAL_FILE (object);
135 g_free (local->filename);
137 G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
140 static void
141 g_local_file_class_init (GLocalFileClass *klass)
143 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
144 GFileAttributeInfoList *list;
146 gobject_class->finalize = g_local_file_finalize;
148 /* Set up attribute lists */
150 /* Writable attributes: */
152 list = g_file_attribute_info_list_new ();
154 g_file_attribute_info_list_add (list,
155 G_FILE_ATTRIBUTE_UNIX_MODE,
156 G_FILE_ATTRIBUTE_TYPE_UINT32,
157 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
158 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
160 #ifdef HAVE_CHOWN
161 g_file_attribute_info_list_add (list,
162 G_FILE_ATTRIBUTE_UNIX_UID,
163 G_FILE_ATTRIBUTE_TYPE_UINT32,
164 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
165 g_file_attribute_info_list_add (list,
166 G_FILE_ATTRIBUTE_UNIX_GID,
167 G_FILE_ATTRIBUTE_TYPE_UINT32,
168 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
169 #endif
171 #ifdef HAVE_SYMLINK
172 g_file_attribute_info_list_add (list,
173 G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
174 G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
176 #endif
178 #ifdef HAVE_UTIMES
179 g_file_attribute_info_list_add (list,
180 G_FILE_ATTRIBUTE_TIME_MODIFIED,
181 G_FILE_ATTRIBUTE_TYPE_UINT64,
182 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
183 g_file_attribute_info_list_add (list,
184 G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
185 G_FILE_ATTRIBUTE_TYPE_UINT32,
186 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
187 g_file_attribute_info_list_add (list,
188 G_FILE_ATTRIBUTE_TIME_ACCESS,
189 G_FILE_ATTRIBUTE_TYPE_UINT64,
190 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
191 g_file_attribute_info_list_add (list,
192 G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
193 G_FILE_ATTRIBUTE_TYPE_UINT32,
194 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
195 #endif
197 local_writable_attributes = list;
199 /* Writable namespaces: */
201 list = g_file_attribute_info_list_new ();
203 #ifdef HAVE_XATTR
204 g_file_attribute_info_list_add (list,
205 "xattr",
206 G_FILE_ATTRIBUTE_TYPE_STRING,
207 G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
208 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
209 g_file_attribute_info_list_add (list,
210 "xattr-sys",
211 G_FILE_ATTRIBUTE_TYPE_STRING,
212 G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
213 #endif
215 local_writable_namespaces = list;
218 static void
219 g_local_file_init (GLocalFile *local)
224 static char *
225 canonicalize_filename (const char *filename)
227 char *canon, *start, *p, *q;
228 char *cwd;
229 int i;
231 if (!g_path_is_absolute (filename))
233 cwd = g_get_current_dir ();
234 canon = g_build_filename (cwd, filename, NULL);
235 g_free (cwd);
237 else
238 canon = g_strdup (filename);
240 start = (char *)g_path_skip_root (canon);
242 /* POSIX allows double slashes at the start to
243 * mean something special (as does windows too).
244 * So, "//" != "/", but more than two slashes
245 * is treated as "/".
247 i = 0;
248 for (p = start - 1;
249 (p >= canon) &&
250 G_IS_DIR_SEPARATOR (*p);
251 p--)
252 i++;
253 if (i > 2)
255 i -= 1;
256 start -= i;
257 memmove (start, start+i, strlen (start+i)+1);
260 p = start;
261 while (*p != 0)
263 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
265 memmove (p, p+1, strlen (p+1)+1);
267 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
269 q = p + 2;
270 /* Skip previous separator */
271 p = p - 2;
272 if (p < start)
273 p = start;
274 while (p > start && !G_IS_DIR_SEPARATOR (*p))
275 p--;
276 if (G_IS_DIR_SEPARATOR (*p))
277 *p++ = G_DIR_SEPARATOR;
278 memmove (p, q, strlen (q)+1);
280 else
282 /* Skip until next separator */
283 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
284 p++;
286 if (*p != 0)
288 /* Canonicalize one separator */
289 *p++ = G_DIR_SEPARATOR;
293 /* Remove additional separators */
294 q = p;
295 while (*q && G_IS_DIR_SEPARATOR (*q))
296 q++;
298 if (p != q)
299 memmove (p, q, strlen (q)+1);
302 /* Remove trailing slashes */
303 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
304 *(p-1) = 0;
306 return canon;
310 * _g_local_file_new:
311 * @filename: filename of the file to create.
313 * Returns: new local #GFile.
315 GFile *
316 _g_local_file_new (const char *filename)
318 GLocalFile *local;
320 local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
321 local->filename = canonicalize_filename (filename);
323 return G_FILE (local);
326 static gboolean
327 g_local_file_is_native (GFile *file)
329 return TRUE;
332 static gboolean
333 g_local_file_has_uri_scheme (GFile *file,
334 const char *uri_scheme)
336 return g_ascii_strcasecmp (uri_scheme, "file") == 0;
339 static char *
340 g_local_file_get_uri_scheme (GFile *file)
342 return g_strdup ("file");
345 static char *
346 g_local_file_get_basename (GFile *file)
348 return g_path_get_basename (G_LOCAL_FILE (file)->filename);
351 static char *
352 g_local_file_get_path (GFile *file)
354 return g_strdup (G_LOCAL_FILE (file)->filename);
357 static char *
358 g_local_file_get_uri (GFile *file)
360 return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
363 static gboolean
364 get_filename_charset (const gchar **filename_charset)
366 const gchar **charsets;
367 gboolean is_utf8;
369 is_utf8 = g_get_filename_charsets (&charsets);
371 if (filename_charset)
372 *filename_charset = charsets[0];
374 return is_utf8;
377 static gboolean
378 name_is_valid_for_display (const char *string,
379 gboolean is_valid_utf8)
381 char c;
383 if (!is_valid_utf8 &&
384 !g_utf8_validate (string, -1, NULL))
385 return FALSE;
387 while ((c = *string++) != 0)
389 if (g_ascii_iscntrl (c))
390 return FALSE;
393 return TRUE;
396 static char *
397 g_local_file_get_parse_name (GFile *file)
399 const char *filename;
400 char *parse_name;
401 const gchar *charset;
402 char *utf8_filename;
403 char *roundtripped_filename;
404 gboolean free_utf8_filename;
405 gboolean is_valid_utf8;
406 char *escaped_path;
408 filename = G_LOCAL_FILE (file)->filename;
409 if (get_filename_charset (&charset))
411 utf8_filename = (char *)filename;
412 free_utf8_filename = FALSE;
413 is_valid_utf8 = FALSE; /* Can't guarantee this */
415 else
417 utf8_filename = g_convert (filename, -1,
418 "UTF-8", charset, NULL, NULL, NULL);
419 free_utf8_filename = TRUE;
420 is_valid_utf8 = TRUE;
422 if (utf8_filename != NULL)
424 /* Make sure we can roundtrip: */
425 roundtripped_filename = g_convert (utf8_filename, -1,
426 charset, "UTF-8", NULL, NULL, NULL);
428 if (roundtripped_filename == NULL ||
429 strcmp (utf8_filename, roundtripped_filename) != 0)
431 g_free (utf8_filename);
432 utf8_filename = NULL;
437 if (utf8_filename != NULL &&
438 name_is_valid_for_display (utf8_filename, is_valid_utf8))
440 if (free_utf8_filename)
441 parse_name = utf8_filename;
442 else
443 parse_name = g_strdup (utf8_filename);
445 else
447 escaped_path = g_uri_escape_string (filename,
448 G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
449 TRUE);
450 parse_name = g_strconcat ("file://",
451 (*escaped_path != '/') ? "/" : "",
452 escaped_path,
453 NULL);
455 g_free (escaped_path);
457 if (free_utf8_filename)
458 g_free (utf8_filename);
461 return parse_name;
464 static GFile *
465 g_local_file_get_parent (GFile *file)
467 GLocalFile *local = G_LOCAL_FILE (file);
468 const char *non_root;
469 char *dirname;
470 GFile *parent;
472 /* Check for root */
473 non_root = g_path_skip_root (local->filename);
474 if (*non_root == 0)
475 return NULL;
477 dirname = g_path_get_dirname (local->filename);
478 parent = _g_local_file_new (dirname);
479 g_free (dirname);
480 return parent;
483 static GFile *
484 g_local_file_dup (GFile *file)
486 GLocalFile *local = G_LOCAL_FILE (file);
488 return _g_local_file_new (local->filename);
491 static guint
492 g_local_file_hash (GFile *file)
494 GLocalFile *local = G_LOCAL_FILE (file);
496 return g_str_hash (local->filename);
499 static gboolean
500 g_local_file_equal (GFile *file1,
501 GFile *file2)
503 GLocalFile *local1 = G_LOCAL_FILE (file1);
504 GLocalFile *local2 = G_LOCAL_FILE (file2);
506 return g_str_equal (local1->filename, local2->filename);
509 static const char *
510 match_prefix (const char *path,
511 const char *prefix)
513 int prefix_len;
515 prefix_len = strlen (prefix);
516 if (strncmp (path, prefix, prefix_len) != 0)
517 return NULL;
519 /* Handle the case where prefix is the root, so that
520 * the IS_DIR_SEPRARATOR check below works */
521 if (prefix_len > 0 &&
522 G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
523 prefix_len--;
525 return path + prefix_len;
528 static gboolean
529 g_local_file_prefix_matches (GFile *parent,
530 GFile *descendant)
532 GLocalFile *parent_local = G_LOCAL_FILE (parent);
533 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
534 const char *remainder;
536 remainder = match_prefix (descendant_local->filename, parent_local->filename);
537 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
538 return TRUE;
539 return FALSE;
542 static char *
543 g_local_file_get_relative_path (GFile *parent,
544 GFile *descendant)
546 GLocalFile *parent_local = G_LOCAL_FILE (parent);
547 GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
548 const char *remainder;
550 remainder = match_prefix (descendant_local->filename, parent_local->filename);
552 if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
553 return g_strdup (remainder + 1);
554 return NULL;
557 static GFile *
558 g_local_file_resolve_relative_path (GFile *file,
559 const char *relative_path)
561 GLocalFile *local = G_LOCAL_FILE (file);
562 char *filename;
563 GFile *child;
565 if (g_path_is_absolute (relative_path))
566 return _g_local_file_new (relative_path);
568 filename = g_build_filename (local->filename, relative_path, NULL);
569 child = _g_local_file_new (filename);
570 g_free (filename);
572 return child;
575 static GFileEnumerator *
576 g_local_file_enumerate_children (GFile *file,
577 const char *attributes,
578 GFileQueryInfoFlags flags,
579 GCancellable *cancellable,
580 GError **error)
582 GLocalFile *local = G_LOCAL_FILE (file);
583 return _g_local_file_enumerator_new (local,
584 attributes, flags,
585 cancellable, error);
588 static GFile *
589 g_local_file_get_child_for_display_name (GFile *file,
590 const char *display_name,
591 GError **error)
593 GFile *parent, *new_file;
594 char *basename;
596 basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
597 if (basename == NULL)
599 g_set_error (error, G_IO_ERROR,
600 G_IO_ERROR_INVALID_FILENAME,
601 _("Invalid filename %s"), display_name);
602 return NULL;
605 parent = g_file_get_parent (file);
606 new_file = g_file_get_child (file, basename);
607 g_object_unref (parent);
608 g_free (basename);
610 return new_file;
613 #ifdef USE_STATFS
614 static const char *
615 get_fs_type (long f_type)
618 /* filesystem ids taken from linux manpage */
619 switch (f_type)
621 case 0xadf5:
622 return "adfs";
623 case 0x5346414f:
624 return "afs";
625 case 0x0187:
626 return "autofs";
627 case 0xADFF:
628 return "affs";
629 case 0x42465331:
630 return "befs";
631 case 0x1BADFACE:
632 return "bfs";
633 case 0xFF534D42:
634 return "cifs";
635 case 0x73757245:
636 return "coda";
637 case 0x012FF7B7:
638 return "coh";
639 case 0x28cd3d45:
640 return "cramfs";
641 case 0x1373:
642 return "devfs";
643 case 0x00414A53:
644 return "efs";
645 case 0x137D:
646 return "ext";
647 case 0xEF51:
648 return "ext2";
649 case 0xEF53:
650 return "ext3";
651 case 0x4244:
652 return "hfs";
653 case 0xF995E849:
654 return "hpfs";
655 case 0x958458f6:
656 return "hugetlbfs";
657 case 0x9660:
658 return "isofs";
659 case 0x72b6:
660 return "jffs2";
661 case 0x3153464a:
662 return "jfs";
663 case 0x137F:
664 return "minix";
665 case 0x138F:
666 return "minix2";
667 case 0x2468:
668 return "minix2";
669 case 0x2478:
670 return "minix22";
671 case 0x4d44:
672 return "msdos";
673 case 0x564c:
674 return "ncp";
675 case 0x6969:
676 return "nfs";
677 case 0x5346544e:
678 return "ntfs";
679 case 0x9fa1:
680 return "openprom";
681 case 0x9fa0:
682 return "proc";
683 case 0x002f:
684 return "qnx4";
685 case 0x52654973:
686 return "reiserfs";
687 case 0x7275:
688 return "romfs";
689 case 0x517B:
690 return "smb";
691 case 0x012FF7B6:
692 return "sysv2";
693 case 0x012FF7B5:
694 return "sysv4";
695 case 0x01021994:
696 return "tmpfs";
697 case 0x15013346:
698 return "udf";
699 case 0x00011954:
700 return "ufs";
701 case 0x9fa2:
702 return "usbdevice";
703 case 0xa501FCF5:
704 return "vxfs";
705 case 0x012FF7B4:
706 return "xenix";
707 case 0x58465342:
708 return "xfs";
709 case 0x012FD16D:
710 return "xiafs";
711 default:
712 return NULL;
715 #endif
717 #ifndef G_OS_WIN32
719 G_LOCK_DEFINE_STATIC(mount_info_hash);
720 static GHashTable *mount_info_hash = NULL;
721 static guint64 mount_info_hash_cache_time = 0;
723 typedef enum {
724 MOUNT_INFO_READONLY = 1<<0
725 } MountInfo;
727 static gboolean
728 device_equal (gconstpointer v1,
729 gconstpointer v2)
731 return *(dev_t *)v1 == *(dev_t *)v2;
734 static guint
735 device_hash (gconstpointer v)
737 return (guint) *(dev_t *)v;
740 static void
741 get_mount_info (GFileInfo *fs_info,
742 const char *path,
743 GFileAttributeMatcher *matcher)
745 struct stat buf;
746 gboolean got_info;
747 gpointer info_as_ptr;
748 guint mount_info;
749 char *mountpoint;
750 dev_t *dev;
751 GUnixMountEntry *mount;
752 guint64 cache_time;
754 if (g_lstat (path, &buf) != 0)
755 return;
757 G_LOCK (mount_info_hash);
759 if (mount_info_hash == NULL)
760 mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
761 g_free, NULL);
764 if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
765 g_hash_table_remove_all (mount_info_hash);
767 got_info = g_hash_table_lookup_extended (mount_info_hash,
768 &buf.st_dev,
769 NULL,
770 &info_as_ptr);
772 G_UNLOCK (mount_info_hash);
774 mount_info = GPOINTER_TO_UINT (info_as_ptr);
776 if (!got_info)
778 mount_info = 0;
780 mountpoint = find_mountpoint_for (path, buf.st_dev);
781 if (mountpoint == NULL)
782 mountpoint = "/";
784 mount = g_unix_mount_at (mountpoint, &cache_time);
785 if (mount)
787 if (g_unix_mount_is_readonly (mount))
788 mount_info |= MOUNT_INFO_READONLY;
790 g_unix_mount_free (mount);
793 dev = g_new0 (dev_t, 1);
794 *dev = buf.st_dev;
796 G_LOCK (mount_info_hash);
797 mount_info_hash_cache_time = cache_time;
798 g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
799 G_UNLOCK (mount_info_hash);
802 if (mount_info & MOUNT_INFO_READONLY)
803 g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
806 #endif
808 #ifdef G_OS_WIN32
810 static gboolean
811 is_xp_or_later (void)
813 static int result = -1;
815 if (result == -1)
817 #ifndef _MSC_VER
818 OSVERSIONINFOEX ver_info = {0};
819 DWORDLONG cond_mask = 0;
820 int op = VER_GREATER_EQUAL;
822 ver_info.dwOSVersionInfoSize = sizeof ver_info;
823 ver_info.dwMajorVersion = 5;
824 ver_info.dwMinorVersion = 1;
826 VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
827 VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
829 result = VerifyVersionInfo (&ver_info,
830 VER_MAJORVERSION | VER_MINORVERSION,
831 cond_mask) != 0;
832 #else
833 result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;
834 #endif
837 return result;
840 static wchar_t *
841 get_volume_for_path (const char *path)
843 long len;
844 wchar_t *wpath;
845 wchar_t *result;
847 wpath = g_utf8_to_utf16 (path, -1, NULL, &len, NULL);
848 result = g_new (wchar_t, len + 2);
850 if (!GetVolumePathNameW (wpath, result, len + 2))
852 char *msg = g_win32_error_message (GetLastError ());
853 g_critical ("GetVolumePathName failed: %s", msg);
854 g_free (msg);
855 g_free (result);
856 g_free (wpath);
857 return NULL;
860 len = wcslen (result);
861 if (len > 0 && result[len-1] != L'\\')
863 result = g_renew (wchar_t, result, len + 2);
864 result[len] = L'\\';
865 result[len + 1] = 0;
868 g_free (wpath);
869 return result;
872 static char *
873 find_mountpoint_for (const char *file, dev_t dev)
875 wchar_t *wpath;
876 char *utf8_path;
878 wpath = get_volume_for_path (file);
879 if (!wpath)
880 return NULL;
882 utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
884 g_free (wpath);
885 return utf8_path;
888 static void
889 get_filesystem_readonly (GFileInfo *info,
890 const char *path)
892 wchar_t *rootdir;
894 rootdir = get_volume_for_path (path);
896 if (rootdir)
898 if (is_xp_or_later ())
900 DWORD flags;
901 if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
902 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
903 (flags & FILE_READ_ONLY_VOLUME) != 0);
905 else
907 if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
908 g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
912 g_free (rootdir);
915 #endif /* G_OS_WIN32 */
917 static GFileInfo *
918 g_local_file_query_filesystem_info (GFile *file,
919 const char *attributes,
920 GCancellable *cancellable,
921 GError **error)
923 GLocalFile *local = G_LOCAL_FILE (file);
924 GFileInfo *info;
925 int statfs_result = 0;
926 gboolean no_size;
927 #ifndef G_OS_WIN32
928 guint64 block_size;
929 const char *fstype;
930 #ifdef USE_STATFS
931 struct statfs statfs_buffer;
932 #elif defined(USE_STATVFS)
933 struct statvfs statfs_buffer;
934 #endif
935 #endif
936 GFileAttributeMatcher *attribute_matcher;
938 no_size = FALSE;
940 #ifdef USE_STATFS
942 #if STATFS_ARGS == 2
943 statfs_result = statfs (local->filename, &statfs_buffer);
944 #elif STATFS_ARGS == 4
945 statfs_result = statfs (local->filename, &statfs_buffer,
946 sizeof (statfs_buffer), 0);
947 #endif
948 block_size = statfs_buffer.f_bsize;
950 #if defined(__linux__)
951 /* ncpfs does not know the amount of available and free space *
952 * assuming ncpfs is linux specific, if you are on a non-linux platform
953 * where ncpfs is available, please file a bug about it on bugzilla.gnome.org
955 if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
956 /* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
957 statfs_buffer.f_type == 0x564c)
958 no_size = TRUE;
959 #endif
961 #elif defined(USE_STATVFS)
962 statfs_result = statvfs (local->filename, &statfs_buffer);
963 block_size = statfs_buffer.f_frsize;
964 #endif
966 if (statfs_result == -1)
968 int errsv = errno;
970 g_set_error (error, G_IO_ERROR,
971 g_io_error_from_errno (errsv),
972 _("Error getting filesystem info: %s"),
973 g_strerror (errsv));
974 return NULL;
977 info = g_file_info_new ();
979 attribute_matcher = g_file_attribute_matcher_new (attributes);
981 if (!no_size &&
982 g_file_attribute_matcher_matches (attribute_matcher,
983 G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
985 #ifdef G_OS_WIN32
986 gchar *localdir = g_path_get_dirname (local->filename);
987 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
988 ULARGE_INTEGER li;
990 g_free (localdir);
991 if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
992 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
993 g_free (wdirname);
994 #else
995 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
996 #endif
998 if (!no_size &&
999 g_file_attribute_matcher_matches (attribute_matcher,
1000 G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1002 #ifdef G_OS_WIN32
1003 gchar *localdir = g_path_get_dirname (local->filename);
1004 wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
1005 ULARGE_INTEGER li;
1007 g_free (localdir);
1008 if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1009 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, (guint64)li.QuadPart);
1010 g_free (wdirname);
1011 #else
1012 g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1013 #endif
1015 #ifdef USE_STATFS
1016 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1017 fstype = g_strdup(statfs_buffer.f_fstypename);
1018 #else
1019 fstype = get_fs_type (statfs_buffer.f_type);
1020 #endif
1022 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1023 fstype = g_strdup(statfs_buffer.f_basetype);
1024 #endif
1026 #ifndef G_OS_WIN32
1027 if (fstype &&
1028 g_file_attribute_matcher_matches (attribute_matcher,
1029 G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1030 g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1031 #endif
1033 if (g_file_attribute_matcher_matches (attribute_matcher,
1034 G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1036 #ifdef G_OS_WIN32
1037 get_filesystem_readonly (info, local->filename);
1038 #else
1039 get_mount_info (info, local->filename, attribute_matcher);
1040 #endif
1043 g_file_attribute_matcher_unref (attribute_matcher);
1045 return info;
1048 static GMount *
1049 g_local_file_find_enclosing_mount (GFile *file,
1050 GCancellable *cancellable,
1051 GError **error)
1053 GLocalFile *local = G_LOCAL_FILE (file);
1054 struct stat buf;
1055 char *mountpoint;
1056 GMount *mount;
1058 if (g_lstat (local->filename, &buf) != 0)
1060 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1061 /* Translators: This is an error message when trying to
1062 * find the enclosing (user visible) mount of a file, but
1063 * none exists. */
1064 _("Containing mount does not exist"));
1065 return NULL;
1068 mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1069 if (mountpoint == NULL)
1071 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1072 /* Translators: This is an error message when trying to
1073 * find the enclosing (user visible) mount of a file, but
1074 * none exists. */
1075 _("Containing mount does not exist"));
1076 return NULL;
1079 mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1080 g_free (mountpoint);
1081 if (mount)
1082 return mount;
1084 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1085 /* Translators: This is an error message when trying to find
1086 * the enclosing (user visible) mount of a file, but none
1087 * exists. */
1088 _("Containing mount does not exist"));
1089 return NULL;
1092 static GFile *
1093 g_local_file_set_display_name (GFile *file,
1094 const char *display_name,
1095 GCancellable *cancellable,
1096 GError **error)
1098 GLocalFile *local, *new_local;
1099 GFile *new_file, *parent;
1100 struct stat statbuf;
1101 int errsv;
1103 parent = g_file_get_parent (file);
1104 if (parent == NULL)
1106 g_set_error_literal (error, G_IO_ERROR,
1107 G_IO_ERROR_FAILED,
1108 _("Can't rename root directory"));
1109 return NULL;
1112 new_file = g_file_get_child_for_display_name (parent, display_name, error);
1113 g_object_unref (parent);
1115 if (new_file == NULL)
1116 return NULL;
1118 local = G_LOCAL_FILE (file);
1119 new_local = G_LOCAL_FILE (new_file);
1121 if (!(g_lstat (new_local->filename, &statbuf) == -1 &&
1122 errno == ENOENT))
1124 g_set_error_literal (error, G_IO_ERROR,
1125 G_IO_ERROR_EXISTS,
1126 _("Can't rename file, filename already exist"));
1127 return NULL;
1130 if (g_rename (local->filename, new_local->filename) == -1)
1132 errsv = errno;
1134 if (errsv == EINVAL)
1135 /* We can't get a rename file into itself error herer,
1136 so this must be an invalid filename, on e.g. FAT */
1137 g_set_error_literal (error, G_IO_ERROR,
1138 G_IO_ERROR_INVALID_FILENAME,
1139 _("Invalid filename"));
1140 else
1141 g_set_error (error, G_IO_ERROR,
1142 g_io_error_from_errno (errsv),
1143 _("Error renaming file: %s"),
1144 g_strerror (errsv));
1145 g_object_unref (new_file);
1146 return NULL;
1149 return new_file;
1152 static GFileInfo *
1153 g_local_file_query_info (GFile *file,
1154 const char *attributes,
1155 GFileQueryInfoFlags flags,
1156 GCancellable *cancellable,
1157 GError **error)
1159 GLocalFile *local = G_LOCAL_FILE (file);
1160 GFileInfo *info;
1161 GFileAttributeMatcher *matcher;
1162 char *basename, *dirname;
1163 GLocalParentFileInfo parent_info;
1165 matcher = g_file_attribute_matcher_new (attributes);
1167 basename = g_path_get_basename (local->filename);
1169 dirname = g_path_get_dirname (local->filename);
1170 _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1171 g_free (dirname);
1173 info = _g_local_file_info_get (basename, local->filename,
1174 matcher, flags, &parent_info,
1175 error);
1177 g_free (basename);
1179 g_file_attribute_matcher_unref (matcher);
1181 return info;
1184 static GFileAttributeInfoList *
1185 g_local_file_query_settable_attributes (GFile *file,
1186 GCancellable *cancellable,
1187 GError **error)
1189 return g_file_attribute_info_list_ref (local_writable_attributes);
1192 static GFileAttributeInfoList *
1193 g_local_file_query_writable_namespaces (GFile *file,
1194 GCancellable *cancellable,
1195 GError **error)
1197 return g_file_attribute_info_list_ref (local_writable_namespaces);
1200 static gboolean
1201 g_local_file_set_attribute (GFile *file,
1202 const char *attribute,
1203 GFileAttributeType type,
1204 gpointer value_p,
1205 GFileQueryInfoFlags flags,
1206 GCancellable *cancellable,
1207 GError **error)
1209 GLocalFile *local = G_LOCAL_FILE (file);
1211 return _g_local_file_info_set_attribute (local->filename,
1212 attribute,
1213 type,
1214 value_p,
1215 flags,
1216 cancellable,
1217 error);
1220 static gboolean
1221 g_local_file_set_attributes_from_info (GFile *file,
1222 GFileInfo *info,
1223 GFileQueryInfoFlags flags,
1224 GCancellable *cancellable,
1225 GError **error)
1227 GLocalFile *local = G_LOCAL_FILE (file);
1228 int res, chained_res;
1229 GFileIface *default_iface;
1231 res = _g_local_file_info_set_attributes (local->filename,
1232 info, flags,
1233 cancellable,
1234 error);
1236 if (!res)
1237 error = NULL; /* Don't write over error if further errors */
1239 default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1241 chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1243 return res && chained_res;
1246 static GFileInputStream *
1247 g_local_file_read (GFile *file,
1248 GCancellable *cancellable,
1249 GError **error)
1251 GLocalFile *local = G_LOCAL_FILE (file);
1252 int fd;
1253 struct stat buf;
1255 fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1256 if (fd == -1)
1258 int errsv = errno;
1260 g_set_error (error, G_IO_ERROR,
1261 g_io_error_from_errno (errsv),
1262 _("Error opening file: %s"),
1263 g_strerror (errsv));
1264 return NULL;
1267 if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
1269 close (fd);
1270 g_set_error_literal (error, G_IO_ERROR,
1271 G_IO_ERROR_IS_DIRECTORY,
1272 _("Can't open directory"));
1273 return NULL;
1276 return _g_local_file_input_stream_new (fd);
1279 static GFileOutputStream *
1280 g_local_file_append_to (GFile *file,
1281 GFileCreateFlags flags,
1282 GCancellable *cancellable,
1283 GError **error)
1285 return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1286 flags, cancellable, error);
1289 static GFileOutputStream *
1290 g_local_file_create (GFile *file,
1291 GFileCreateFlags flags,
1292 GCancellable *cancellable,
1293 GError **error)
1295 return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1296 flags, cancellable, error);
1299 static GFileOutputStream *
1300 g_local_file_replace (GFile *file,
1301 const char *etag,
1302 gboolean make_backup,
1303 GFileCreateFlags flags,
1304 GCancellable *cancellable,
1305 GError **error)
1307 return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1308 etag, make_backup, flags,
1309 cancellable, error);
1313 static gboolean
1314 g_local_file_delete (GFile *file,
1315 GCancellable *cancellable,
1316 GError **error)
1318 GLocalFile *local = G_LOCAL_FILE (file);
1320 if (g_remove (local->filename) == -1)
1322 int errsv = errno;
1324 /* Posix allows EEXIST too, but the more sane error
1325 is G_IO_ERROR_NOT_FOUND, and its what nautilus
1326 expects */
1327 if (errsv == EEXIST)
1328 errsv = ENOTEMPTY;
1330 g_set_error (error, G_IO_ERROR,
1331 g_io_error_from_errno (errsv),
1332 _("Error removing file: %s"),
1333 g_strerror (errsv));
1334 return FALSE;
1337 return TRUE;
1340 static char *
1341 strip_trailing_slashes (const char *path)
1343 char *path_copy;
1344 int len;
1346 path_copy = g_strdup (path);
1347 len = strlen (path_copy);
1348 while (len > 1 && path_copy[len-1] == '/')
1349 path_copy[--len] = 0;
1351 return path_copy;
1354 static char *
1355 expand_symlink (const char *link)
1357 char *resolved, *canonical, *parent, *link2;
1358 char symlink_value[4096];
1359 #ifdef G_OS_WIN32
1360 #else
1361 ssize_t res;
1362 #endif
1364 #ifdef G_OS_WIN32
1365 #else
1366 res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1368 if (res == -1)
1369 return g_strdup (link);
1370 symlink_value[res] = 0;
1371 #endif
1373 if (g_path_is_absolute (symlink_value))
1374 return canonicalize_filename (symlink_value);
1375 else
1377 link2 = strip_trailing_slashes (link);
1378 parent = g_path_get_dirname (link2);
1379 g_free (link2);
1381 resolved = g_build_filename (parent, symlink_value, NULL);
1382 g_free (parent);
1384 canonical = canonicalize_filename (resolved);
1386 g_free (resolved);
1388 return canonical;
1392 static char *
1393 get_parent (const char *path,
1394 dev_t *parent_dev)
1396 char *parent, *tmp;
1397 struct stat parent_stat;
1398 int num_recursions;
1399 char *path_copy;
1401 path_copy = strip_trailing_slashes (path);
1403 parent = g_path_get_dirname (path_copy);
1404 if (strcmp (parent, ".") == 0 ||
1405 strcmp (parent, path_copy) == 0)
1407 g_free (parent);
1408 g_free (path_copy);
1409 return NULL;
1411 g_free (path_copy);
1413 num_recursions = 0;
1414 do {
1415 if (g_lstat (parent, &parent_stat) != 0)
1417 g_free (parent);
1418 return NULL;
1421 if (S_ISLNK (parent_stat.st_mode))
1423 tmp = parent;
1424 parent = expand_symlink (parent);
1425 g_free (tmp);
1428 num_recursions++;
1429 if (num_recursions > 12)
1431 g_free (parent);
1432 return NULL;
1434 } while (S_ISLNK (parent_stat.st_mode));
1436 *parent_dev = parent_stat.st_dev;
1438 return parent;
1441 static char *
1442 expand_all_symlinks (const char *path)
1444 char *parent, *parent_expanded;
1445 char *basename, *res;
1446 dev_t parent_dev;
1448 parent = get_parent (path, &parent_dev);
1449 if (parent)
1451 parent_expanded = expand_all_symlinks (parent);
1452 g_free (parent);
1453 basename = g_path_get_basename (path);
1454 res = g_build_filename (parent_expanded, basename, NULL);
1455 g_free (basename);
1456 g_free (parent_expanded);
1458 else
1459 res = g_strdup (path);
1461 return res;
1464 #ifndef G_OS_WIN32
1466 static char *
1467 find_mountpoint_for (const char *file,
1468 dev_t dev)
1470 char *dir, *parent;
1471 dev_t dir_dev, parent_dev;
1473 dir = g_strdup (file);
1474 dir_dev = dev;
1476 while (1)
1478 parent = get_parent (dir, &parent_dev);
1479 if (parent == NULL)
1480 return dir;
1482 if (parent_dev != dir_dev)
1484 g_free (parent);
1485 return dir;
1488 g_free (dir);
1489 dir = parent;
1493 static char *
1494 find_topdir_for (const char *file)
1496 char *dir;
1497 dev_t dir_dev;
1499 dir = get_parent (file, &dir_dev);
1500 if (dir == NULL)
1501 return NULL;
1503 return find_mountpoint_for (dir, dir_dev);
1506 static char *
1507 get_unique_filename (const char *basename,
1508 int id)
1510 const char *dot;
1512 if (id == 1)
1513 return g_strdup (basename);
1515 dot = strchr (basename, '.');
1516 if (dot)
1517 return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1518 else
1519 return g_strdup_printf ("%s.%d", basename, id);
1522 static gboolean
1523 path_has_prefix (const char *path,
1524 const char *prefix)
1526 int prefix_len;
1528 if (prefix == NULL)
1529 return TRUE;
1531 prefix_len = strlen (prefix);
1533 if (strncmp (path, prefix, prefix_len) == 0 &&
1534 (prefix_len == 0 || /* empty prefix always matches */
1535 prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1536 path[prefix_len] == 0 ||
1537 path[prefix_len] == '/'))
1538 return TRUE;
1540 return FALSE;
1543 static char *
1544 try_make_relative (const char *path,
1545 const char *base)
1547 char *path2, *base2;
1548 char *relative;
1550 path2 = expand_all_symlinks (path);
1551 base2 = expand_all_symlinks (base);
1553 relative = NULL;
1554 if (path_has_prefix (path2, base2))
1556 relative = path2 + strlen (base2);
1557 while (*relative == '/')
1558 relative ++;
1559 relative = g_strdup (relative);
1561 g_free (path2);
1562 g_free (base2);
1564 if (relative)
1565 return relative;
1567 /* Failed, use abs path */
1568 return g_strdup (path);
1571 static char *
1572 escape_trash_name (char *name)
1574 GString *str;
1575 const gchar hex[16] = "0123456789ABCDEF";
1577 str = g_string_new ("");
1579 while (*name != 0)
1581 char c;
1583 c = *name++;
1585 if (g_ascii_isprint (c))
1586 g_string_append_c (str, c);
1587 else
1589 g_string_append_c (str, '%');
1590 g_string_append_c (str, hex[((guchar)c) >> 4]);
1591 g_string_append_c (str, hex[((guchar)c) & 0xf]);
1595 return g_string_free (str, FALSE);
1598 gboolean
1599 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1601 static gsize home_dev_set = 0;
1602 static dev_t home_dev;
1603 char *topdir, *globaldir, *trashdir, *tmpname;
1604 uid_t uid;
1605 char uid_str[32];
1606 struct stat global_stat, trash_stat;
1607 gboolean res;
1608 int statres;
1610 if (g_once_init_enter (&home_dev_set))
1612 struct stat home_stat;
1614 g_stat (g_get_home_dir (), &home_stat);
1615 home_dev = home_stat.st_dev;
1616 g_once_init_leave (&home_dev_set, 1);
1619 /* Assume we can trash to the home */
1620 if (dir_dev == home_dev)
1621 return TRUE;
1623 topdir = find_mountpoint_for (dirname, dir_dev);
1624 if (topdir == NULL)
1625 return FALSE;
1627 globaldir = g_build_filename (topdir, ".Trash", NULL);
1628 statres = g_lstat (globaldir, &global_stat);
1629 if (g_lstat (globaldir, &global_stat) == 0 &&
1630 S_ISDIR (global_stat.st_mode) &&
1631 (global_stat.st_mode & S_ISVTX) != 0)
1633 /* got a toplevel sysadmin created dir, assume we
1634 * can trash to it (we should be able to create a dir)
1635 * This fails for the FAT case where the ownership of
1636 * that dir would be wrong though..
1638 g_free (globaldir);
1639 g_free (topdir);
1640 return TRUE;
1642 g_free (globaldir);
1644 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1645 uid = geteuid ();
1646 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1648 tmpname = g_strdup_printf (".Trash-%s", uid_str);
1649 trashdir = g_build_filename (topdir, tmpname, NULL);
1650 g_free (tmpname);
1652 if (g_lstat (trashdir, &trash_stat) == 0)
1654 g_free (topdir);
1655 g_free (trashdir);
1656 return
1657 S_ISDIR (trash_stat.st_mode) &&
1658 trash_stat.st_uid == uid;
1660 g_free (trashdir);
1662 /* User specific trash didn't exist, can we create it? */
1663 res = g_access (topdir, W_OK) == 0;
1665 g_free (topdir);
1667 return res;
1671 static gboolean
1672 g_local_file_trash (GFile *file,
1673 GCancellable *cancellable,
1674 GError **error)
1676 GLocalFile *local = G_LOCAL_FILE (file);
1677 struct stat file_stat, home_stat;
1678 const char *homedir;
1679 char *trashdir, *topdir, *infodir, *filesdir;
1680 char *basename, *trashname, *trashfile, *infoname, *infofile;
1681 char *original_name, *original_name_escaped;
1682 int i;
1683 char *data;
1684 gboolean is_homedir_trash;
1685 char delete_time[32];
1686 int fd;
1687 struct stat trash_stat, global_stat;
1688 char *dirname, *globaldir;
1690 if (g_lstat (local->filename, &file_stat) != 0)
1692 int errsv = errno;
1694 g_set_error (error, G_IO_ERROR,
1695 g_io_error_from_errno (errsv),
1696 _("Error trashing file: %s"),
1697 g_strerror (errsv));
1698 return FALSE;
1701 homedir = g_get_home_dir ();
1702 g_stat (homedir, &home_stat);
1704 is_homedir_trash = FALSE;
1705 trashdir = NULL;
1706 if (file_stat.st_dev == home_stat.st_dev)
1708 is_homedir_trash = TRUE;
1709 errno = 0;
1710 trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1711 if (g_mkdir_with_parents (trashdir, 0700) < 0)
1713 char *display_name;
1714 int errsv = errno;
1716 display_name = g_filename_display_name (trashdir);
1717 g_set_error (error, G_IO_ERROR,
1718 g_io_error_from_errno (errsv),
1719 _("Unable to create trash dir %s: %s"),
1720 display_name, g_strerror (errsv));
1721 g_free (display_name);
1722 g_free (trashdir);
1723 return FALSE;
1725 topdir = g_strdup (g_get_user_data_dir ());
1727 else
1729 uid_t uid;
1730 char uid_str[32];
1732 uid = geteuid ();
1733 g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1735 topdir = find_topdir_for (local->filename);
1736 if (topdir == NULL)
1738 g_set_error_literal (error, G_IO_ERROR,
1739 G_IO_ERROR_NOT_SUPPORTED,
1740 _("Unable to find toplevel directory for trash"));
1741 return FALSE;
1744 /* Try looking for global trash dir $topdir/.Trash/$uid */
1745 globaldir = g_build_filename (topdir, ".Trash", NULL);
1746 if (g_lstat (globaldir, &global_stat) == 0 &&
1747 S_ISDIR (global_stat.st_mode) &&
1748 (global_stat.st_mode & S_ISVTX) != 0)
1750 trashdir = g_build_filename (globaldir, uid_str, NULL);
1752 if (g_lstat (trashdir, &trash_stat) == 0)
1754 if (!S_ISDIR (trash_stat.st_mode) ||
1755 trash_stat.st_uid != uid)
1757 /* Not a directory or not owned by user, ignore */
1758 g_free (trashdir);
1759 trashdir = NULL;
1762 else if (g_mkdir (trashdir, 0700) == -1)
1764 g_free (trashdir);
1765 trashdir = NULL;
1768 g_free (globaldir);
1770 if (trashdir == NULL)
1772 gboolean tried_create;
1774 /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1775 dirname = g_strdup_printf (".Trash-%s", uid_str);
1776 trashdir = g_build_filename (topdir, dirname, NULL);
1777 g_free (dirname);
1779 tried_create = FALSE;
1781 retry:
1782 if (g_lstat (trashdir, &trash_stat) == 0)
1784 if (!S_ISDIR (trash_stat.st_mode) ||
1785 trash_stat.st_uid != uid)
1787 /* Remove the failed directory */
1788 if (tried_create)
1789 g_remove (trashdir);
1791 /* Not a directory or not owned by user, ignore */
1792 g_free (trashdir);
1793 trashdir = NULL;
1796 else
1798 if (!tried_create &&
1799 g_mkdir (trashdir, 0700) != -1)
1801 /* Ensure that the created dir has the right uid etc.
1802 This might fail on e.g. a FAT dir */
1803 tried_create = TRUE;
1804 goto retry;
1806 else
1808 g_free (trashdir);
1809 trashdir = NULL;
1814 if (trashdir == NULL)
1816 g_free (topdir);
1817 g_set_error_literal (error, G_IO_ERROR,
1818 G_IO_ERROR_NOT_SUPPORTED,
1819 _("Unable to find or create trash directory"));
1820 return FALSE;
1824 /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1826 infodir = g_build_filename (trashdir, "info", NULL);
1827 filesdir = g_build_filename (trashdir, "files", NULL);
1828 g_free (trashdir);
1830 /* Make sure we have the subdirectories */
1831 if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1832 (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1834 g_free (topdir);
1835 g_free (infodir);
1836 g_free (filesdir);
1837 g_set_error_literal (error, G_IO_ERROR,
1838 G_IO_ERROR_NOT_SUPPORTED,
1839 _("Unable to find or create trash directory"));
1840 return FALSE;
1843 basename = g_path_get_basename (local->filename);
1844 i = 1;
1845 trashname = NULL;
1846 infofile = NULL;
1847 do {
1848 g_free (trashname);
1849 g_free (infofile);
1851 trashname = get_unique_filename (basename, i++);
1852 infoname = g_strconcat (trashname, ".trashinfo", NULL);
1853 infofile = g_build_filename (infodir, infoname, NULL);
1854 g_free (infoname);
1856 fd = open (infofile, O_CREAT | O_EXCL, 0666);
1857 } while (fd == -1 && errno == EEXIST);
1859 g_free (basename);
1860 g_free (infodir);
1862 if (fd == -1)
1864 int errsv = errno;
1866 g_free (filesdir);
1867 g_free (topdir);
1868 g_free (trashname);
1869 g_free (infofile);
1871 g_set_error (error, G_IO_ERROR,
1872 g_io_error_from_errno (errsv),
1873 _("Unable to create trashing info file: %s"),
1874 g_strerror (errsv));
1875 return FALSE;
1878 close (fd);
1880 /* TODO: Maybe we should verify that you can delete the file from the trash
1881 before moving it? OTOH, that is hard, as it needs a recursive scan */
1883 trashfile = g_build_filename (filesdir, trashname, NULL);
1885 g_free (filesdir);
1887 if (g_rename (local->filename, trashfile) == -1)
1889 int errsv = errno;
1891 g_free (topdir);
1892 g_free (trashname);
1893 g_free (infofile);
1894 g_free (trashfile);
1896 g_set_error (error, G_IO_ERROR,
1897 g_io_error_from_errno (errsv),
1898 _("Unable to trash file: %s"),
1899 g_strerror (errsv));
1900 return FALSE;
1903 g_free (trashfile);
1905 /* TODO: Do we need to update mtime/atime here after the move? */
1907 /* Use absolute names for homedir */
1908 if (is_homedir_trash)
1909 original_name = g_strdup (local->filename);
1910 else
1911 original_name = try_make_relative (local->filename, topdir);
1912 original_name_escaped = escape_trash_name (original_name);
1914 g_free (original_name);
1915 g_free (topdir);
1918 time_t t;
1919 struct tm now;
1920 t = time (NULL);
1921 localtime_r (&t, &now);
1922 delete_time[0] = 0;
1923 strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
1926 data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
1927 original_name_escaped, delete_time);
1929 g_file_set_contents (infofile, data, -1, NULL);
1930 g_free (infofile);
1931 g_free (data);
1933 g_free (original_name_escaped);
1934 g_free (trashname);
1936 return TRUE;
1938 #else /* G_OS_WIN32 */
1939 gboolean
1940 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1942 return FALSE; /* XXX ??? */
1945 static gboolean
1946 g_local_file_trash (GFile *file,
1947 GCancellable *cancellable,
1948 GError **error)
1950 GLocalFile *local = G_LOCAL_FILE (file);
1951 SHFILEOPSTRUCTW op = {0};
1952 gboolean success;
1953 wchar_t *wfilename;
1954 long len;
1956 wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
1957 /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
1958 wfilename = g_renew (wchar_t, wfilename, len + 2);
1959 wfilename[len + 1] = 0;
1961 op.wFunc = FO_DELETE;
1962 op.pFrom = wfilename;
1963 op.fFlags = FOF_ALLOWUNDO;
1965 success = SHFileOperationW (&op) == 0;
1967 if (success && op.fAnyOperationsAborted)
1969 if (cancellable && !g_cancellable_is_cancelled (cancellable))
1970 g_cancellable_cancel (cancellable);
1971 g_set_error (error, G_IO_ERROR,
1972 G_IO_ERROR_CANCELLED,
1973 _("Unable to trash file: %s"),
1974 _("Operation was cancelled"));
1975 success = FALSE;
1977 else if (!success)
1978 g_set_error (error, G_IO_ERROR,
1979 G_IO_ERROR_FAILED,
1980 _("Unable to trash file: %s"),
1981 _("internal error"));
1983 g_free (wfilename);
1984 return success;
1986 #endif /* G_OS_WIN32 */
1988 static gboolean
1989 g_local_file_make_directory (GFile *file,
1990 GCancellable *cancellable,
1991 GError **error)
1993 GLocalFile *local = G_LOCAL_FILE (file);
1995 if (g_mkdir (local->filename, 0755) == -1)
1997 int errsv = errno;
1999 if (errsv == EINVAL)
2000 /* This must be an invalid filename, on e.g. FAT */
2001 g_set_error_literal (error, G_IO_ERROR,
2002 G_IO_ERROR_INVALID_FILENAME,
2003 _("Invalid filename"));
2004 else
2005 g_set_error (error, G_IO_ERROR,
2006 g_io_error_from_errno (errsv),
2007 _("Error creating directory: %s"),
2008 g_strerror (errsv));
2009 return FALSE;
2012 return TRUE;
2015 static gboolean
2016 g_local_file_make_symbolic_link (GFile *file,
2017 const char *symlink_value,
2018 GCancellable *cancellable,
2019 GError **error)
2021 #ifdef HAVE_SYMLINK
2022 GLocalFile *local = G_LOCAL_FILE (file);
2024 if (symlink (symlink_value, local->filename) == -1)
2026 int errsv = errno;
2028 if (errsv == EINVAL)
2029 /* This must be an invalid filename, on e.g. FAT */
2030 g_set_error_literal (error, G_IO_ERROR,
2031 G_IO_ERROR_INVALID_FILENAME,
2032 _("Invalid filename"));
2033 else
2034 g_set_error (error, G_IO_ERROR,
2035 g_io_error_from_errno (errsv),
2036 _("Error making symbolic link: %s"),
2037 g_strerror (errsv));
2038 return FALSE;
2040 return TRUE;
2041 #else
2042 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
2043 return FALSE;
2044 #endif
2048 static gboolean
2049 g_local_file_copy (GFile *source,
2050 GFile *destination,
2051 GFileCopyFlags flags,
2052 GCancellable *cancellable,
2053 GFileProgressCallback progress_callback,
2054 gpointer progress_callback_data,
2055 GError **error)
2057 /* Fall back to default copy */
2058 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2059 return FALSE;
2062 static gboolean
2063 g_local_file_move (GFile *source,
2064 GFile *destination,
2065 GFileCopyFlags flags,
2066 GCancellable *cancellable,
2067 GFileProgressCallback progress_callback,
2068 gpointer progress_callback_data,
2069 GError **error)
2071 GLocalFile *local_source, *local_destination;
2072 struct stat statbuf;
2073 gboolean destination_exist, source_is_dir;
2074 char *backup_name;
2075 int res;
2076 off_t source_size;
2078 if (!G_IS_LOCAL_FILE (source) ||
2079 !G_IS_LOCAL_FILE (destination))
2081 /* Fall back to default move */
2082 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2083 return FALSE;
2086 local_source = G_LOCAL_FILE (source);
2087 local_destination = G_LOCAL_FILE (destination);
2089 res = g_lstat (local_source->filename, &statbuf);
2090 if (res == -1)
2092 int errsv = errno;
2094 g_set_error (error, G_IO_ERROR,
2095 g_io_error_from_errno (errsv),
2096 _("Error moving file: %s"),
2097 g_strerror (errsv));
2098 return FALSE;
2101 source_is_dir = S_ISDIR (statbuf.st_mode);
2102 source_size = statbuf.st_size;
2104 destination_exist = FALSE;
2105 res = g_lstat (local_destination->filename, &statbuf);
2106 if (res == 0)
2108 destination_exist = TRUE; /* Target file exists */
2110 if (flags & G_FILE_COPY_OVERWRITE)
2112 /* Always fail on dirs, even with overwrite */
2113 if (S_ISDIR (statbuf.st_mode))
2115 if (source_is_dir)
2116 g_set_error_literal (error,
2117 G_IO_ERROR,
2118 G_IO_ERROR_WOULD_MERGE,
2119 _("Can't move directory over directory"));
2120 else
2121 g_set_error_literal (error,
2122 G_IO_ERROR,
2123 G_IO_ERROR_IS_DIRECTORY,
2124 _("Can't copy over directory"));
2125 return FALSE;
2128 else
2130 g_set_error_literal (error,
2131 G_IO_ERROR,
2132 G_IO_ERROR_EXISTS,
2133 _("Target file exists"));
2134 return FALSE;
2138 if (flags & G_FILE_COPY_BACKUP && destination_exist)
2140 backup_name = g_strconcat (local_destination->filename, "~", NULL);
2141 if (g_rename (local_destination->filename, backup_name) == -1)
2143 g_set_error_literal (error,
2144 G_IO_ERROR,
2145 G_IO_ERROR_CANT_CREATE_BACKUP,
2146 _("Backup file creation failed"));
2147 g_free (backup_name);
2148 return FALSE;
2150 g_free (backup_name);
2151 destination_exist = FALSE; /* It did, but no more */
2154 if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2156 /* Source is a dir, destination exists (and is not a dir, because that would have failed
2157 earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2158 res = g_unlink (local_destination->filename);
2159 if (res == -1)
2161 int errsv = errno;
2163 g_set_error (error, G_IO_ERROR,
2164 g_io_error_from_errno (errsv),
2165 _("Error removing target file: %s"),
2166 g_strerror (errsv));
2167 return FALSE;
2171 if (g_rename (local_source->filename, local_destination->filename) == -1)
2173 int errsv = errno;
2175 if (errsv == EXDEV)
2176 /* This will cause the fallback code to run */
2177 g_set_error_literal (error, G_IO_ERROR,
2178 G_IO_ERROR_NOT_SUPPORTED,
2179 _("Move between mounts not supported"));
2180 else if (errsv == EINVAL)
2181 /* This must be an invalid filename, on e.g. FAT, or
2182 we're trying to move the file into itself...
2183 We return invalid filename for both... */
2184 g_set_error_literal (error, G_IO_ERROR,
2185 G_IO_ERROR_INVALID_FILENAME,
2186 _("Invalid filename"));
2187 else
2188 g_set_error (error, G_IO_ERROR,
2189 g_io_error_from_errno (errsv),
2190 _("Error moving file: %s"),
2191 g_strerror (errsv));
2192 return FALSE;
2195 /* Make sure we send full copied size */
2196 if (progress_callback)
2197 progress_callback (source_size, source_size, progress_callback_data);
2199 return TRUE;
2202 static GFileMonitor*
2203 g_local_file_monitor_dir (GFile *file,
2204 GFileMonitorFlags flags,
2205 GCancellable *cancellable,
2206 GError **error)
2208 GLocalFile* local_file = G_LOCAL_FILE(file);
2209 return _g_local_directory_monitor_new (local_file->filename, flags, error);
2212 static GFileMonitor*
2213 g_local_file_monitor_file (GFile *file,
2214 GFileMonitorFlags flags,
2215 GCancellable *cancellable,
2216 GError **error)
2218 GLocalFile* local_file = G_LOCAL_FILE(file);
2219 return _g_local_file_monitor_new (local_file->filename, flags, error);
2222 static void
2223 g_local_file_file_iface_init (GFileIface *iface)
2225 iface->dup = g_local_file_dup;
2226 iface->hash = g_local_file_hash;
2227 iface->equal = g_local_file_equal;
2228 iface->is_native = g_local_file_is_native;
2229 iface->has_uri_scheme = g_local_file_has_uri_scheme;
2230 iface->get_uri_scheme = g_local_file_get_uri_scheme;
2231 iface->get_basename = g_local_file_get_basename;
2232 iface->get_path = g_local_file_get_path;
2233 iface->get_uri = g_local_file_get_uri;
2234 iface->get_parse_name = g_local_file_get_parse_name;
2235 iface->get_parent = g_local_file_get_parent;
2236 iface->prefix_matches = g_local_file_prefix_matches;
2237 iface->get_relative_path = g_local_file_get_relative_path;
2238 iface->resolve_relative_path = g_local_file_resolve_relative_path;
2239 iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2240 iface->set_display_name = g_local_file_set_display_name;
2241 iface->enumerate_children = g_local_file_enumerate_children;
2242 iface->query_info = g_local_file_query_info;
2243 iface->query_filesystem_info = g_local_file_query_filesystem_info;
2244 iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2245 iface->query_settable_attributes = g_local_file_query_settable_attributes;
2246 iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2247 iface->set_attribute = g_local_file_set_attribute;
2248 iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2249 iface->read_fn = g_local_file_read;
2250 iface->append_to = g_local_file_append_to;
2251 iface->create = g_local_file_create;
2252 iface->replace = g_local_file_replace;
2253 iface->delete_file = g_local_file_delete;
2254 iface->trash = g_local_file_trash;
2255 iface->make_directory = g_local_file_make_directory;
2256 iface->make_symbolic_link = g_local_file_make_symbolic_link;
2257 iface->copy = g_local_file_copy;
2258 iface->move = g_local_file_move;
2259 iface->monitor_dir = g_local_file_monitor_dir;
2260 iface->monitor_file = g_local_file_monitor_file;