Bug 536252 – GFileEnumerator should allow access to the containing GFile
[platform/upstream/glib.git] / gio / glocalfile.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include <config.h>
24
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
33
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
48
49 #ifndef O_BINARY
50 #define O_BINARY 0
51 #endif
52
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(sun) && defined(__SVR4)
57    /* on solaris, 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
64
65 #elif defined(HAVE_STATFS)
66
67 # define USE_STATFS
68
69 #elif defined(HAVE_STATVFS)
70
71 # define USE_STATVFS
72
73 #endif
74
75 #include "glocalfile.h"
76 #include "glocalfileinfo.h"
77 #include "glocalfileenumerator.h"
78 #include "glocalfileinputstream.h"
79 #include "glocalfileoutputstream.h"
80 #include "glocaldirectorymonitor.h"
81 #include "glocalfilemonitor.h"
82 #include "gmountprivate.h"
83 #include <glib/gstdio.h>
84 #include "glibintl.h"
85
86 #ifdef G_OS_WIN32
87 #define _WIN32_WINNT 0x0500
88 #include <windows.h>
89 #include <io.h>
90 #include <direct.h>
91
92 #ifndef FILE_READ_ONLY_VOLUME
93 #define FILE_READ_ONLY_VOLUME           0x00080000
94 #endif
95
96 #ifndef S_ISDIR
97 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
98 #endif
99 #ifndef S_ISLNK
100 #define S_ISLNK(m) (0)
101 #endif
102 #endif
103
104 #include "gioalias.h"
105
106 static void g_local_file_file_iface_init (GFileIface *iface);
107
108 static GFileAttributeInfoList *local_writable_attributes = NULL;
109 static GFileAttributeInfoList *local_writable_namespaces = NULL;
110
111 struct _GLocalFile
112 {
113   GObject parent_instance;
114
115   char *filename;
116 };
117
118 #define g_local_file_get_type _g_local_file_get_type
119 G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
120                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
121                                                 g_local_file_file_iface_init))
122
123 static char *find_mountpoint_for (const char *file, dev_t dev);
124
125 static void
126 g_local_file_finalize (GObject *object)
127 {
128   GLocalFile *local;
129
130   local = G_LOCAL_FILE (object);
131
132   g_free (local->filename);
133   
134   if (G_OBJECT_CLASS (g_local_file_parent_class)->finalize)
135     (*G_OBJECT_CLASS (g_local_file_parent_class)->finalize) (object);
136 }
137
138 static void
139 g_local_file_class_init (GLocalFileClass *klass)
140 {
141   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
142   GFileAttributeInfoList *list;
143
144   gobject_class->finalize = g_local_file_finalize;
145
146   /* Set up attribute lists */
147
148   /* Writable attributes: */
149
150   list = g_file_attribute_info_list_new ();
151
152   g_file_attribute_info_list_add (list,
153                                   G_FILE_ATTRIBUTE_UNIX_MODE,
154                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
155                                   G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
156                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
157   
158 #ifdef HAVE_CHOWN
159   g_file_attribute_info_list_add (list,
160                                   G_FILE_ATTRIBUTE_UNIX_UID,
161                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
162                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
163   g_file_attribute_info_list_add (list,
164                                   G_FILE_ATTRIBUTE_UNIX_GID,
165                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
166                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
167 #endif
168   
169 #ifdef HAVE_SYMLINK
170   g_file_attribute_info_list_add (list,
171                                   G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
172                                   G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
173                                   0);
174 #endif
175   
176 #ifdef HAVE_UTIMES
177   g_file_attribute_info_list_add (list,
178                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
179                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
180                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
181   g_file_attribute_info_list_add (list,
182                                   G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
183                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
184                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
185   g_file_attribute_info_list_add (list,
186                                   G_FILE_ATTRIBUTE_TIME_ACCESS,
187                                   G_FILE_ATTRIBUTE_TYPE_UINT64,
188                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
189   g_file_attribute_info_list_add (list,
190                                   G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
191                                   G_FILE_ATTRIBUTE_TYPE_UINT32,
192                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
193 #endif
194
195   local_writable_attributes = list;
196
197   /* Writable namespaces: */
198   
199   list = g_file_attribute_info_list_new ();
200
201 #ifdef HAVE_XATTR
202   g_file_attribute_info_list_add (list,
203                                   "xattr",
204                                   G_FILE_ATTRIBUTE_TYPE_STRING,
205                                   G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
206                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
207   g_file_attribute_info_list_add (list,
208                                   "xattr-sys",
209                                   G_FILE_ATTRIBUTE_TYPE_STRING,
210                                   G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
211 #endif
212
213   local_writable_namespaces = list;
214 }
215
216 static void
217 g_local_file_init (GLocalFile *local)
218 {
219 }
220
221
222 static char *
223 canonicalize_filename (const char *filename)
224 {
225   char *canon, *start, *p, *q;
226   char *cwd;
227   int i;
228   
229   if (!g_path_is_absolute (filename))
230     {
231       cwd = g_get_current_dir ();
232       canon = g_build_filename (cwd, filename, NULL);
233       g_free (cwd);
234     }
235   else
236     canon = g_strdup (filename);
237
238   start = (char *)g_path_skip_root (canon);
239
240   /* POSIX allows double slashes at the start to
241    * mean something special (as does windows too).
242    * So, "//" != "/", but more than two slashes
243    * is treated as "/".
244    */
245   i = 0;
246   for (p = start - 1;
247        (p >= canon) &&
248          G_IS_DIR_SEPARATOR (*p);
249        p--)
250     i++;
251   if (i > 2)
252     {
253       i -= 1;
254       start -= i;
255       memmove (start, start+i, strlen (start+i)+1);
256     }
257   
258   p = start;
259   while (*p != 0)
260     {
261       if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
262         {
263           memmove (p, p+1, strlen (p+1)+1);
264         }
265       else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
266         {
267           q = p + 2;
268           /* Skip previous separator */
269           p = p - 2;
270           if (p < start)
271             p = start;
272           while (p > start && !G_IS_DIR_SEPARATOR (*p))
273             p--;
274           if (G_IS_DIR_SEPARATOR (*p))
275             *p++ = G_DIR_SEPARATOR;
276           memmove (p, q, strlen (q)+1);
277         }
278       else
279         {
280           /* Skip until next separator */
281           while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
282             p++;
283           
284           if (*p != 0)
285             {
286               /* Canonicalize one separator */
287               *p++ = G_DIR_SEPARATOR;
288             }
289         }
290
291       /* Remove additional separators */
292       q = p;
293       while (*q && G_IS_DIR_SEPARATOR (*q))
294         q++;
295
296       if (p != q)
297         memmove (p, q, strlen (q)+1);
298     }
299
300   /* Remove trailing slashes */
301   if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
302     *(p-1) = 0;
303   
304   return canon;
305 }
306
307 /**
308  * _g_local_file_new:
309  * @filename: filename of the file to create.
310  * 
311  * Returns: new local #GFile.
312  **/
313 GFile *
314 _g_local_file_new (const char *filename)
315 {
316   GLocalFile *local;
317
318   local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
319   local->filename = canonicalize_filename (filename);
320   
321   return G_FILE (local);
322 }
323
324 static gboolean
325 g_local_file_is_native (GFile *file)
326 {
327   return TRUE;
328 }
329
330 static gboolean
331 g_local_file_has_uri_scheme (GFile      *file,
332                              const char *uri_scheme)
333 {
334   return g_ascii_strcasecmp (uri_scheme, "file") == 0;
335 }
336
337 static char *
338 g_local_file_get_uri_scheme (GFile *file)
339 {
340   return g_strdup ("file");
341 }
342
343 static char *
344 g_local_file_get_basename (GFile *file)
345 {
346   return g_path_get_basename (G_LOCAL_FILE (file)->filename);
347 }
348
349 static char *
350 g_local_file_get_path (GFile *file)
351 {
352   return g_strdup (G_LOCAL_FILE (file)->filename);
353 }
354
355 static char *
356 g_local_file_get_uri (GFile *file)
357 {
358   return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
359 }
360
361 static gboolean
362 get_filename_charset (const gchar **filename_charset)
363 {
364   const gchar **charsets;
365   gboolean is_utf8;
366   
367   is_utf8 = g_get_filename_charsets (&charsets);
368
369   if (filename_charset)
370     *filename_charset = charsets[0];
371   
372   return is_utf8;
373 }
374
375 static gboolean
376 name_is_valid_for_display (const char *string,
377                            gboolean    is_valid_utf8)
378 {
379   char c;
380
381   if (!is_valid_utf8 &&
382       !g_utf8_validate (string, -1, NULL))
383     return FALSE;
384
385   while ((c = *string++) != 0)
386     {
387       if (g_ascii_iscntrl (c))
388         return FALSE;
389     }
390
391   return TRUE;
392 }
393
394 static char *
395 g_local_file_get_parse_name (GFile *file)
396 {
397   const char *filename;
398   char *parse_name;
399   const gchar *charset;
400   char *utf8_filename;
401   char *roundtripped_filename;
402   gboolean free_utf8_filename;
403   gboolean is_valid_utf8;
404   char *escaped_path;
405   
406   filename = G_LOCAL_FILE (file)->filename;
407   if (get_filename_charset (&charset))
408     {
409       utf8_filename = (char *)filename;
410       free_utf8_filename = FALSE;
411       is_valid_utf8 = FALSE; /* Can't guarantee this */
412     }
413   else
414     {
415       utf8_filename = g_convert (filename, -1, 
416                                  "UTF-8", charset, NULL, NULL, NULL);
417       free_utf8_filename = TRUE;
418       is_valid_utf8 = TRUE;
419
420       if (utf8_filename != NULL)
421         {
422           /* Make sure we can roundtrip: */
423           roundtripped_filename = g_convert (utf8_filename, -1,
424                                              charset, "UTF-8", NULL, NULL, NULL);
425           
426           if (roundtripped_filename == NULL ||
427               strcmp (utf8_filename, roundtripped_filename) != 0)
428             {
429               g_free (utf8_filename);
430               utf8_filename = NULL;
431             }
432         }
433     }
434
435   if (utf8_filename != NULL &&
436       name_is_valid_for_display (utf8_filename, is_valid_utf8))
437     {
438       if (free_utf8_filename)
439         parse_name = utf8_filename;
440       else
441         parse_name = g_strdup (utf8_filename);
442     }
443   else
444     {
445       escaped_path = g_uri_escape_string (filename,
446                                           G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
447                                           TRUE);
448       parse_name = g_strconcat ("file://",
449                                 (*escaped_path != '/') ? "/" : "",
450                                 escaped_path,
451                                 NULL);
452       
453       g_free (escaped_path);
454
455       if (free_utf8_filename)
456         g_free (utf8_filename);
457     }
458   
459   return parse_name;
460 }
461
462 static GFile *
463 g_local_file_get_parent (GFile *file)
464 {
465   GLocalFile *local = G_LOCAL_FILE (file);
466   const char *non_root;
467   char *dirname;
468   GFile *parent;
469
470   /* Check for root */
471   non_root = g_path_skip_root (local->filename);
472   if (*non_root == 0)
473     return NULL;
474
475   dirname = g_path_get_dirname (local->filename);
476   parent = _g_local_file_new (dirname);
477   g_free (dirname);
478   return parent;
479 }
480
481 static GFile *
482 g_local_file_dup (GFile *file)
483 {
484   GLocalFile *local = G_LOCAL_FILE (file);
485
486   return _g_local_file_new (local->filename);
487 }
488
489 static guint
490 g_local_file_hash (GFile *file)
491 {
492   GLocalFile *local = G_LOCAL_FILE (file);
493   
494   return g_str_hash (local->filename);
495 }
496
497 static gboolean
498 g_local_file_equal (GFile *file1,
499                     GFile *file2)
500 {
501   GLocalFile *local1 = G_LOCAL_FILE (file1);
502   GLocalFile *local2 = G_LOCAL_FILE (file2);
503
504   return g_str_equal (local1->filename, local2->filename);
505 }
506
507 static const char *
508 match_prefix (const char *path, 
509               const char *prefix)
510 {
511   int prefix_len;
512
513   prefix_len = strlen (prefix);
514   if (strncmp (path, prefix, prefix_len) != 0)
515     return NULL;
516   
517   /* Handle the case where prefix is the root, so that
518    * the IS_DIR_SEPRARATOR check below works */
519   if (prefix_len > 0 &&
520       G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
521     prefix_len--;
522   
523   return path + prefix_len;
524 }
525
526 static gboolean
527 g_local_file_prefix_matches (GFile *parent,
528                              GFile *descendant)
529 {
530   GLocalFile *parent_local = G_LOCAL_FILE (parent);
531   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
532   const char *remainder;
533
534   remainder = match_prefix (descendant_local->filename, parent_local->filename);
535   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
536     return TRUE;
537   return FALSE;
538 }
539
540 static char *
541 g_local_file_get_relative_path (GFile *parent,
542                                 GFile *descendant)
543 {
544   GLocalFile *parent_local = G_LOCAL_FILE (parent);
545   GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
546   const char *remainder;
547
548   remainder = match_prefix (descendant_local->filename, parent_local->filename);
549   
550   if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
551     return g_strdup (remainder + 1);
552   return NULL;
553 }
554
555 static GFile *
556 g_local_file_resolve_relative_path (GFile      *file,
557                                     const char *relative_path)
558 {
559   GLocalFile *local = G_LOCAL_FILE (file);
560   char *filename;
561   GFile *child;
562
563   if (g_path_is_absolute (relative_path))
564     return _g_local_file_new (relative_path);
565   
566   filename = g_build_filename (local->filename, relative_path, NULL);
567   child = _g_local_file_new (filename);
568   g_free (filename);
569   
570   return child;
571 }
572
573 static GFileEnumerator *
574 g_local_file_enumerate_children (GFile                *file,
575                                  const char           *attributes,
576                                  GFileQueryInfoFlags   flags,
577                                  GCancellable         *cancellable,
578                                  GError              **error)
579 {
580   GLocalFile *local = G_LOCAL_FILE (file);
581   return _g_local_file_enumerator_new (local,
582                                        attributes, flags,
583                                        cancellable, error);
584 }
585
586 static GFile *
587 g_local_file_get_child_for_display_name (GFile        *file,
588                                          const char   *display_name,
589                                          GError      **error)
590 {
591   GFile *parent, *new_file;
592   char *basename;
593
594   basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
595   if (basename == NULL)
596     {
597       g_set_error (error, G_IO_ERROR,
598                    G_IO_ERROR_INVALID_FILENAME,
599                    _("Invalid filename %s"), display_name);
600       return NULL;
601     }
602
603   parent = g_file_get_parent (file);
604   new_file = g_file_get_child (file, basename);
605   g_object_unref (parent);
606   g_free (basename);
607   
608   return new_file;
609 }
610
611 #ifdef USE_STATFS
612 static const char *
613 get_fs_type (long f_type)
614 {
615
616   /* filesystem ids taken from linux manpage */
617   switch (f_type) 
618     {
619     case 0xadf5:
620       return "adfs";
621     case 0x5346414f:
622       return "afs";
623     case 0x0187:
624       return "autofs";
625     case 0xADFF:
626       return "affs";
627     case 0x42465331:
628       return "befs";
629     case 0x1BADFACE:
630       return "bfs";
631     case 0xFF534D42:
632       return "cifs";
633     case 0x73757245:
634       return "coda";
635     case 0x012FF7B7:
636       return "coh";
637     case 0x28cd3d45:
638       return "cramfs";
639     case 0x1373:
640       return "devfs";
641     case 0x00414A53:
642       return "efs";
643     case 0x137D:
644       return "ext";
645     case 0xEF51:
646       return "ext2";
647     case 0xEF53:
648       return "ext3";
649     case 0x4244:
650       return "hfs";
651     case 0xF995E849:
652       return "hpfs";
653     case 0x958458f6:
654       return "hugetlbfs";
655     case 0x9660:
656       return "isofs";
657     case 0x72b6:
658       return "jffs2";
659     case 0x3153464a:
660       return "jfs";
661     case 0x137F:
662       return "minix";
663     case 0x138F:
664       return "minix2";
665     case 0x2468:
666       return "minix2";
667     case 0x2478:
668       return "minix22";
669     case 0x4d44:
670       return "msdos";
671     case 0x564c:
672       return "ncp";
673     case 0x6969:
674       return "nfs";
675     case 0x5346544e:
676       return "ntfs";
677     case 0x9fa1:
678       return "openprom";
679     case 0x9fa0:
680       return "proc";
681     case 0x002f:
682       return "qnx4";
683     case 0x52654973:
684       return "reiserfs";
685     case 0x7275:
686       return "romfs";
687     case 0x517B:
688       return "smb";
689     case 0x012FF7B6:
690       return "sysv2";
691     case 0x012FF7B5:
692       return "sysv4";
693     case 0x01021994:
694       return "tmpfs";
695     case 0x15013346:
696       return "udf";
697     case 0x00011954:
698       return "ufs";
699     case 0x9fa2:
700       return "usbdevice";
701     case 0xa501FCF5:
702       return "vxfs";
703     case 0x012FF7B4:
704       return "xenix";
705     case 0x58465342:
706       return "xfs";
707     case 0x012FD16D:
708       return "xiafs";
709     default:
710       return NULL;
711     }
712 }
713 #endif
714
715 #ifndef G_OS_WIN32
716
717 G_LOCK_DEFINE_STATIC(mount_info_hash);
718 static GHashTable *mount_info_hash = NULL;
719 static guint64 mount_info_hash_cache_time = 0;
720
721 typedef enum {
722   MOUNT_INFO_READONLY = 1<<0
723 } MountInfo;
724
725 static gboolean
726 device_equal (gconstpointer v1,
727               gconstpointer v2)
728 {
729   return *(dev_t *)v1 == *(dev_t *)v2;
730 }
731
732 static guint
733 device_hash (gconstpointer v)
734 {
735   return (guint) *(dev_t *)v;
736 }
737
738 static void
739 get_mount_info (GFileInfo             *fs_info,
740                 const char            *path,
741                 GFileAttributeMatcher *matcher)
742 {
743   struct stat buf;
744   gboolean got_info;
745   gpointer info_as_ptr;
746   guint mount_info;
747   char *mountpoint;
748   dev_t *dev;
749   GUnixMountEntry *mount;
750   guint64 cache_time;
751
752   if (g_lstat (path, &buf) != 0)
753     return;
754
755   G_LOCK (mount_info_hash);
756
757   if (mount_info_hash == NULL)
758     mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
759                                              g_free, NULL);
760
761
762   if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
763     g_hash_table_remove_all (mount_info_hash);
764   
765   got_info = g_hash_table_lookup_extended (mount_info_hash,
766                                            &buf.st_dev,
767                                            NULL,
768                                            &info_as_ptr);
769   
770   G_UNLOCK (mount_info_hash);
771   
772   mount_info = GPOINTER_TO_UINT (info_as_ptr);
773   
774   if (!got_info)
775     {
776       mount_info = 0;
777
778       mountpoint = find_mountpoint_for (path, buf.st_dev);
779       if (mountpoint == NULL)
780         mountpoint = "/";
781
782       mount = g_unix_mount_at (mountpoint, &cache_time);
783       if (mount)
784         {
785           if (g_unix_mount_is_readonly (mount))
786             mount_info |= MOUNT_INFO_READONLY;
787           
788           g_unix_mount_free (mount);
789         }
790
791       dev = g_new0 (dev_t, 1);
792       *dev = buf.st_dev;
793       
794       G_LOCK (mount_info_hash);
795       mount_info_hash_cache_time = cache_time;
796       g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
797       G_UNLOCK (mount_info_hash);
798     }
799
800   if (mount_info & MOUNT_INFO_READONLY)
801     g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
802 }
803
804 #endif
805
806 #ifdef G_OS_WIN32
807
808 static gboolean
809 is_xp_or_later (void)
810 {
811   static int result = -1;
812
813   if (result == -1)
814     {
815       OSVERSIONINFOEX ver_info = {0};
816       DWORDLONG cond_mask = 0;
817       int op = VER_GREATER_EQUAL;
818
819       ver_info.dwOSVersionInfoSize = sizeof ver_info;
820       ver_info.dwMajorVersion = 5;
821       ver_info.dwMinorVersion = 1;
822
823       VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
824       VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);
825
826       result = VerifyVersionInfo (&ver_info,
827                                   VER_MAJORVERSION | VER_MINORVERSION, 
828                                   cond_mask) != 0;
829     }
830
831   return result;
832 }
833
834 static wchar_t *
835 get_volume_for_path (const char *path)
836 {
837   long len;
838   wchar_t *wpath;
839   wchar_t *result;
840
841   wpath = g_utf8_to_utf16 (path, -1, NULL, &len, NULL);
842   result = g_new (wchar_t, len + 2);
843
844   if (!GetVolumePathNameW (wpath, result, len + 2))
845     {
846       char *msg = g_win32_error_message (GetLastError ());
847       g_critical ("GetVolumePathName failed: %s", msg);
848       g_free (msg);
849       g_free (result);
850       g_free (wpath);
851       return NULL;
852     }
853
854   len = wcslen (result);
855   if (len > 0 && result[len-1] != L'\\')
856     {
857       result = g_renew (wchar_t, result, len + 2);
858       result[len] = L'\\';
859       result[len + 1] = 0;
860     }
861
862   g_free (wpath);
863   return result;
864 }
865
866 static char *
867 find_mountpoint_for (const char *file, dev_t dev)
868 {
869   wchar_t *wpath;
870   char *utf8_path;
871
872   wpath = get_volume_for_path (file);
873   if (!wpath)
874     return NULL;
875
876   utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);
877
878   g_free (wpath);
879   return utf8_path;
880 }
881
882 static void
883 get_filesystem_readonly (GFileInfo  *info,
884                          const char *path)
885 {
886   wchar_t *rootdir;
887
888   rootdir = get_volume_for_path (path);
889
890   if (rootdir)
891     {
892       if (is_xp_or_later ())
893         {
894           DWORD flags;
895           if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
896             g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
897                                                (flags & FILE_READ_ONLY_VOLUME) != 0);
898         }
899       else
900         {
901           if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
902             g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
903         }
904     }
905
906   g_free (rootdir);
907 }
908
909 #endif /* G_OS_WIN32 */
910
911 static GFileInfo *
912 g_local_file_query_filesystem_info (GFile         *file,
913                                     const char    *attributes,
914                                     GCancellable  *cancellable,
915                                     GError       **error)
916 {
917   GLocalFile *local = G_LOCAL_FILE (file);
918   GFileInfo *info;
919   int statfs_result;
920   gboolean no_size;
921 #ifndef G_OS_WIN32
922   guint64 block_size;
923   const char *fstype;
924 #ifdef USE_STATFS
925   struct statfs statfs_buffer;
926 #elif defined(USE_STATVFS)
927   struct statvfs statfs_buffer;
928 #endif
929 #endif
930   GFileAttributeMatcher *attribute_matcher;
931         
932   no_size = FALSE;
933   
934 #ifdef USE_STATFS
935   
936 #if STATFS_ARGS == 2
937   statfs_result = statfs (local->filename, &statfs_buffer);
938 #elif STATFS_ARGS == 4
939   statfs_result = statfs (local->filename, &statfs_buffer,
940                           sizeof (statfs_buffer), 0);
941 #endif
942   block_size = statfs_buffer.f_bsize;
943   
944 #if defined(__linux__)
945   /* ncpfs does not know the amount of available and free space *
946    * assuming ncpfs is linux specific, if you are on a non-linux platform
947    * where ncpfs is available, please file a bug about it on bugzilla.gnome.org
948    */
949   if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
950       /* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
951       statfs_buffer.f_type == 0x564c)
952     no_size = TRUE;
953 #endif
954   
955 #elif defined(USE_STATVFS)
956   statfs_result = statvfs (local->filename, &statfs_buffer);
957   block_size = statfs_buffer.f_frsize; 
958 #endif
959
960   if (statfs_result == -1)
961     {
962       int errsv = errno;
963
964       g_set_error (error, G_IO_ERROR,
965                    g_io_error_from_errno (errsv),
966                    _("Error getting filesystem info: %s"),
967                    g_strerror (errsv));
968       return NULL;
969     }
970
971   info = g_file_info_new ();
972
973   attribute_matcher = g_file_attribute_matcher_new (attributes);
974   
975   if (!no_size &&
976       g_file_attribute_matcher_matches (attribute_matcher,
977                                         G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
978     {
979 #ifdef G_OS_WIN32
980       gchar *localdir = g_path_get_dirname (local->filename);
981       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
982       ULARGE_INTEGER li;
983       
984       g_free (localdir);
985       if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
986         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
987       g_free (wdirname);
988 #else
989       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
990 #endif
991     }
992   if (!no_size &&
993       g_file_attribute_matcher_matches (attribute_matcher,
994                                         G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
995     {
996 #ifdef G_OS_WIN32
997       gchar *localdir = g_path_get_dirname (local->filename);
998       wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
999       ULARGE_INTEGER li;
1000       
1001       g_free (localdir);
1002       if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1003         g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,  (guint64)li.QuadPart);
1004       g_free (wdirname);
1005 #else
1006       g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1007 #endif
1008     }
1009 #ifdef USE_STATFS
1010 #if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1011   fstype = g_strdup(statfs_buffer.f_fstypename);
1012 #else
1013   fstype = get_fs_type (statfs_buffer.f_type);
1014 #endif
1015
1016 #elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
1017   fstype = g_strdup(statfs_buffer.f_basetype); 
1018 #endif
1019
1020 #ifndef G_OS_WIN32
1021   if (fstype &&
1022       g_file_attribute_matcher_matches (attribute_matcher,
1023                                         G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
1024     g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1025 #endif  
1026
1027   if (g_file_attribute_matcher_matches (attribute_matcher,
1028                                         G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1029     {
1030 #ifdef G_OS_WIN32
1031       get_filesystem_readonly (info, local->filename);
1032 #else
1033       get_mount_info (info, local->filename, attribute_matcher);
1034 #endif
1035     }
1036   
1037   g_file_attribute_matcher_unref (attribute_matcher);
1038   
1039   return info;
1040 }
1041
1042 static GMount *
1043 g_local_file_find_enclosing_mount (GFile         *file,
1044                                    GCancellable  *cancellable,
1045                                    GError       **error)
1046 {
1047   GLocalFile *local = G_LOCAL_FILE (file);
1048   struct stat buf;
1049   char *mountpoint;
1050   GMount *mount;
1051
1052   if (g_lstat (local->filename, &buf) != 0)
1053     {
1054       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1055                       /* Translators: This is an error message when trying to
1056                        * find the enclosing (user visible) mount of a file, but
1057                        * none exists. */
1058                       _("Containing mount does not exist"));
1059       return NULL;
1060     }
1061
1062   mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
1063   if (mountpoint == NULL)
1064     {
1065       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1066                       /* Translators: This is an error message when trying to
1067                        * find the enclosing (user visible) mount of a file, but
1068                        * none exists. */
1069                       _("Containing mount does not exist"));
1070       return NULL;
1071     }
1072
1073   mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1074   g_free (mountpoint);
1075   if (mount)
1076     return mount;
1077
1078   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1079                   /* Translators: This is an error message when trying to find
1080                    * the enclosing (user visible) mount of a file, but none
1081                    * exists. */
1082                   _("Containing mount does not exist"));
1083   return NULL;
1084 }
1085
1086 static GFile *
1087 g_local_file_set_display_name (GFile         *file,
1088                                const char    *display_name,
1089                                GCancellable  *cancellable,
1090                                GError       **error)
1091 {
1092   GLocalFile *local, *new_local;
1093   GFile *new_file, *parent;
1094   struct stat statbuf;
1095   int errsv;
1096
1097   parent = g_file_get_parent (file);
1098   if (parent == NULL)
1099     {
1100       g_set_error (error, G_IO_ERROR,
1101                    G_IO_ERROR_FAILED,
1102                    _("Can't rename root directory"));
1103       return NULL;
1104     }
1105   
1106   new_file = g_file_get_child_for_display_name (parent, display_name, error);
1107   g_object_unref (parent);
1108   
1109   if (new_file == NULL)
1110     return NULL;
1111   
1112   local = G_LOCAL_FILE (file);
1113   new_local = G_LOCAL_FILE (new_file);
1114
1115   if (!(g_lstat (new_local->filename, &statbuf) == -1 &&
1116         errno == ENOENT))
1117     {
1118       g_set_error (error, G_IO_ERROR,
1119                    G_IO_ERROR_EXISTS,
1120                    _("Can't rename file, filename already exist"));
1121       return NULL;
1122     }
1123
1124   if (g_rename (local->filename, new_local->filename) == -1)
1125     {
1126       errsv = errno;
1127
1128       if (errsv == EINVAL)
1129         /* We can't get a rename file into itself error herer,
1130            so this must be an invalid filename, on e.g. FAT */
1131         g_set_error (error, G_IO_ERROR,
1132                      G_IO_ERROR_INVALID_FILENAME,
1133                      _("Invalid filename"));
1134       else
1135         g_set_error (error, G_IO_ERROR,
1136                      g_io_error_from_errno (errsv),
1137                      _("Error renaming file: %s"),
1138                      g_strerror (errsv));
1139       g_object_unref (new_file);
1140       return NULL;
1141     }
1142   
1143   return new_file;
1144 }
1145
1146 static GFileInfo *
1147 g_local_file_query_info (GFile                *file,
1148                          const char           *attributes,
1149                          GFileQueryInfoFlags   flags,
1150                          GCancellable         *cancellable,
1151                          GError              **error)
1152 {
1153   GLocalFile *local = G_LOCAL_FILE (file);
1154   GFileInfo *info;
1155   GFileAttributeMatcher *matcher;
1156   char *basename, *dirname;
1157   GLocalParentFileInfo parent_info;
1158
1159   matcher = g_file_attribute_matcher_new (attributes);
1160   
1161   basename = g_path_get_basename (local->filename);
1162   
1163   dirname = g_path_get_dirname (local->filename);
1164   _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
1165   g_free (dirname);
1166   
1167   info = _g_local_file_info_get (basename, local->filename,
1168                                  matcher, flags, &parent_info,
1169                                  error);
1170   
1171   g_free (basename);
1172
1173   g_file_attribute_matcher_unref (matcher);
1174
1175   return info;
1176 }
1177
1178 static GFileAttributeInfoList *
1179 g_local_file_query_settable_attributes (GFile         *file,
1180                                         GCancellable  *cancellable,
1181                                         GError       **error)
1182 {
1183   return g_file_attribute_info_list_ref (local_writable_attributes);
1184 }
1185
1186 static GFileAttributeInfoList *
1187 g_local_file_query_writable_namespaces (GFile         *file,
1188                                         GCancellable  *cancellable,
1189                                         GError       **error)
1190 {
1191   return g_file_attribute_info_list_ref (local_writable_namespaces);
1192 }
1193
1194 static gboolean
1195 g_local_file_set_attribute (GFile                *file,
1196                             const char           *attribute,
1197                             GFileAttributeType    type,
1198                             gpointer              value_p,
1199                             GFileQueryInfoFlags   flags,
1200                             GCancellable         *cancellable,
1201                             GError              **error)
1202 {
1203   GLocalFile *local = G_LOCAL_FILE (file);
1204
1205   return _g_local_file_info_set_attribute (local->filename,
1206                                            attribute,
1207                                            type,
1208                                            value_p,
1209                                            flags,
1210                                            cancellable,
1211                                            error);
1212 }
1213
1214 static gboolean
1215 g_local_file_set_attributes_from_info (GFile                *file,
1216                                        GFileInfo            *info,
1217                                        GFileQueryInfoFlags   flags,
1218                                        GCancellable         *cancellable,
1219                                        GError              **error)
1220 {
1221   GLocalFile *local = G_LOCAL_FILE (file);
1222   int res, chained_res;
1223   GFileIface *default_iface;
1224
1225   res = _g_local_file_info_set_attributes (local->filename,
1226                                            info, flags, 
1227                                            cancellable,
1228                                            error);
1229
1230   if (!res)
1231     error = NULL; /* Don't write over error if further errors */
1232
1233   default_iface = g_type_default_interface_peek (G_TYPE_FILE);
1234
1235   chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
1236   
1237   return res && chained_res;
1238 }
1239
1240 static GFileInputStream *
1241 g_local_file_read (GFile         *file,
1242                    GCancellable  *cancellable,
1243                    GError       **error)
1244 {
1245   GLocalFile *local = G_LOCAL_FILE (file);
1246   int fd;
1247   struct stat buf;
1248   
1249   fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1250   if (fd == -1)
1251     {
1252       int errsv = errno;
1253
1254       g_set_error (error, G_IO_ERROR,
1255                    g_io_error_from_errno (errsv),
1256                    _("Error opening file: %s"),
1257                    g_strerror (errsv));
1258       return NULL;
1259     }
1260
1261   if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
1262     {
1263       close (fd);
1264       g_set_error (error, G_IO_ERROR,
1265                    G_IO_ERROR_IS_DIRECTORY,
1266                    _("Can't open directory"));
1267       return NULL;
1268     }
1269   
1270   return _g_local_file_input_stream_new (fd);
1271 }
1272
1273 static GFileOutputStream *
1274 g_local_file_append_to (GFile             *file,
1275                         GFileCreateFlags   flags,
1276                         GCancellable      *cancellable,
1277                         GError           **error)
1278 {
1279   return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
1280                                              flags, cancellable, error);
1281 }
1282
1283 static GFileOutputStream *
1284 g_local_file_create (GFile             *file,
1285                      GFileCreateFlags   flags,
1286                      GCancellable      *cancellable,
1287                      GError           **error)
1288 {
1289   return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1290                                              flags, cancellable, error);
1291 }
1292
1293 static GFileOutputStream *
1294 g_local_file_replace (GFile             *file,
1295                       const char        *etag,
1296                       gboolean           make_backup,
1297                       GFileCreateFlags   flags,
1298                       GCancellable      *cancellable,
1299                       GError           **error)
1300 {
1301   return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1302                                               etag, make_backup, flags,
1303                                               cancellable, error);
1304 }
1305
1306
1307 static gboolean
1308 g_local_file_delete (GFile         *file,
1309                      GCancellable  *cancellable,
1310                      GError       **error)
1311 {
1312   GLocalFile *local = G_LOCAL_FILE (file);
1313   
1314   if (g_remove (local->filename) == -1)
1315     {
1316       int errsv = errno;
1317
1318       /* Posix allows EEXIST too, but the more sane error
1319          is G_IO_ERROR_NOT_FOUND, and its what nautilus
1320          expects */
1321       if (errsv == EEXIST)
1322         errsv = ENOTEMPTY;
1323
1324       g_set_error (error, G_IO_ERROR,
1325                    g_io_error_from_errno (errsv),
1326                    _("Error removing file: %s"),
1327                    g_strerror (errsv));
1328       return FALSE;
1329     }
1330   
1331   return TRUE;
1332 }
1333
1334 static char *
1335 strip_trailing_slashes (const char *path)
1336 {
1337   char *path_copy;
1338   int len;
1339
1340   path_copy = g_strdup (path);
1341   len = strlen (path_copy);
1342   while (len > 1 && path_copy[len-1] == '/')
1343     path_copy[--len] = 0;
1344
1345   return path_copy;
1346  }
1347
1348 static char *
1349 expand_symlink (const char *link)
1350 {
1351   char *resolved, *canonical, *parent, *link2;
1352   char symlink_value[4096];
1353 #ifdef G_OS_WIN32
1354 #else
1355   ssize_t res;
1356 #endif
1357   
1358 #ifdef G_OS_WIN32
1359 #else
1360   res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1361   
1362   if (res == -1)
1363     return g_strdup (link);
1364   symlink_value[res] = 0;
1365 #endif
1366   
1367   if (g_path_is_absolute (symlink_value))
1368     return canonicalize_filename (symlink_value);
1369   else
1370     {
1371       link2 = strip_trailing_slashes (link);
1372       parent = g_path_get_dirname (link2);
1373       g_free (link2);
1374       
1375       resolved = g_build_filename (parent, symlink_value, NULL);
1376       g_free (parent);
1377       
1378       canonical = canonicalize_filename (resolved);
1379       
1380       g_free (resolved);
1381
1382       return canonical;
1383     }
1384 }
1385
1386 static char *
1387 get_parent (const char *path, 
1388             dev_t      *parent_dev)
1389 {
1390   char *parent, *tmp;
1391   struct stat parent_stat;
1392   int num_recursions;
1393   char *path_copy;
1394
1395   path_copy = strip_trailing_slashes (path);
1396   
1397   parent = g_path_get_dirname (path_copy);
1398   if (strcmp (parent, ".") == 0 ||
1399       strcmp (parent, path_copy) == 0)
1400     {
1401       g_free (parent);
1402       g_free (path_copy);
1403       return NULL;
1404     }
1405   g_free (path_copy);
1406
1407   num_recursions = 0;
1408   do {
1409     if (g_lstat (parent, &parent_stat) != 0)
1410       {
1411         g_free (parent);
1412         return NULL;
1413       }
1414     
1415     if (S_ISLNK (parent_stat.st_mode))
1416       {
1417         tmp = parent;
1418         parent = expand_symlink (parent);
1419         g_free (tmp);
1420       }
1421     
1422     num_recursions++;
1423     if (num_recursions > 12)
1424       {
1425         g_free (parent);
1426         return NULL;
1427       }
1428   } while (S_ISLNK (parent_stat.st_mode));
1429
1430   *parent_dev = parent_stat.st_dev;
1431   
1432   return parent;
1433 }
1434
1435 static char *
1436 expand_all_symlinks (const char *path)
1437 {
1438   char *parent, *parent_expanded;
1439   char *basename, *res;
1440   dev_t parent_dev;
1441
1442   parent = get_parent (path, &parent_dev);
1443   if (parent)
1444     {
1445       parent_expanded = expand_all_symlinks (parent);
1446       g_free (parent);
1447       basename = g_path_get_basename (path);
1448       res = g_build_filename (parent_expanded, basename, NULL);
1449       g_free (basename);
1450       g_free (parent_expanded);
1451     }
1452   else
1453     res = g_strdup (path);
1454   
1455   return res;
1456 }
1457
1458 #ifndef G_OS_WIN32
1459
1460 static char *
1461 find_mountpoint_for (const char *file, 
1462                      dev_t       dev)
1463 {
1464   char *dir, *parent;
1465   dev_t dir_dev, parent_dev;
1466
1467   dir = g_strdup (file);
1468   dir_dev = dev;
1469
1470   while (1) 
1471     {
1472       parent = get_parent (dir, &parent_dev);
1473       if (parent == NULL)
1474         return dir;
1475     
1476       if (parent_dev != dir_dev)
1477         {
1478           g_free (parent);
1479           return dir;
1480         }
1481     
1482       g_free (dir);
1483       dir = parent;
1484     }
1485 }
1486
1487 static char *
1488 find_topdir_for (const char *file)
1489 {
1490   char *dir;
1491   dev_t dir_dev;
1492
1493   dir = get_parent (file, &dir_dev);
1494   if (dir == NULL)
1495     return NULL;
1496
1497   return find_mountpoint_for (dir, dir_dev);
1498 }
1499
1500 static char *
1501 get_unique_filename (const char *basename, 
1502                      int         id)
1503 {
1504   const char *dot;
1505       
1506   if (id == 1)
1507     return g_strdup (basename);
1508
1509   dot = strchr (basename, '.');
1510   if (dot)
1511     return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1512   else
1513     return g_strdup_printf ("%s.%d", basename, id);
1514 }
1515
1516 static gboolean
1517 path_has_prefix (const char *path, 
1518                  const char *prefix)
1519 {
1520   int prefix_len;
1521
1522   if (prefix == NULL)
1523     return TRUE;
1524
1525   prefix_len = strlen (prefix);
1526   
1527   if (strncmp (path, prefix, prefix_len) == 0 &&
1528       (prefix_len == 0 || /* empty prefix always matches */
1529        prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
1530        path[prefix_len] == 0 ||
1531        path[prefix_len] == '/'))
1532     return TRUE;
1533   
1534   return FALSE;
1535 }
1536
1537 static char *
1538 try_make_relative (const char *path, 
1539                    const char *base)
1540 {
1541   char *path2, *base2;
1542   char *relative;
1543
1544   path2 = expand_all_symlinks (path);
1545   base2 = expand_all_symlinks (base);
1546
1547   relative = NULL;
1548   if (path_has_prefix (path2, base2))
1549     {
1550       relative = path2 + strlen (base2);
1551       while (*relative == '/')
1552         relative ++;
1553       relative = g_strdup (relative);
1554     }
1555   g_free (path2);
1556   g_free (base2);
1557
1558   if (relative)
1559     return relative;
1560   
1561   /* Failed, use abs path */
1562   return g_strdup (path);
1563 }
1564
1565 static char *
1566 escape_trash_name (char *name)
1567 {
1568   GString *str;
1569   const gchar hex[16] = "0123456789ABCDEF";
1570   
1571   str = g_string_new ("");
1572
1573   while (*name != 0)
1574     {
1575       char c;
1576
1577       c = *name++;
1578
1579       if (g_ascii_isprint (c))
1580         g_string_append_c (str, c);
1581       else
1582         {
1583           g_string_append_c (str, '%');
1584           g_string_append_c (str, hex[((guchar)c) >> 4]);
1585           g_string_append_c (str, hex[((guchar)c) & 0xf]);
1586         }
1587     }
1588
1589   return g_string_free (str, FALSE);
1590 }
1591
1592 gboolean
1593 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1594 {
1595   static gsize home_dev_set = 0;
1596   static dev_t home_dev;
1597   char *topdir, *globaldir, *trashdir, *tmpname;
1598   uid_t uid;
1599   char uid_str[32];
1600   struct stat global_stat, trash_stat;
1601   gboolean res;
1602   int statres;
1603       
1604   if (g_once_init_enter (&home_dev_set))
1605     {
1606       struct stat home_stat;
1607       
1608       g_stat (g_get_home_dir (), &home_stat);
1609       home_dev = home_stat.st_dev;
1610       g_once_init_leave (&home_dev_set, 1);
1611     }
1612
1613   /* Assume we can trash to the home */
1614   if (dir_dev == home_dev)
1615     return TRUE;
1616
1617   topdir = find_mountpoint_for (dirname, dir_dev);
1618   if (topdir == NULL)
1619     return FALSE;
1620
1621   globaldir = g_build_filename (topdir, ".Trash", NULL); 
1622   statres = g_lstat (globaldir, &global_stat);
1623  if (g_lstat (globaldir, &global_stat) == 0 &&
1624       S_ISDIR (global_stat.st_mode) &&
1625       (global_stat.st_mode & S_ISVTX) != 0)
1626     {
1627       /* got a toplevel sysadmin created dir, assume we
1628        * can trash to it (we should be able to create a dir)
1629        * This fails for the FAT case where the ownership of
1630        * that dir would be wrong though..
1631        */
1632       g_free (globaldir);
1633       g_free (topdir);
1634       return TRUE;
1635     }
1636   g_free (globaldir);
1637
1638   /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1639   uid = geteuid ();
1640   g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
1641   
1642   tmpname = g_strdup_printf (".Trash-%s", uid_str);
1643   trashdir = g_build_filename (topdir, tmpname, NULL);
1644   g_free (tmpname);
1645
1646   if (g_lstat (trashdir, &trash_stat) == 0)
1647     {
1648       g_free (topdir);
1649       g_free (trashdir);
1650       return
1651         S_ISDIR (trash_stat.st_mode) &&
1652         trash_stat.st_uid == uid;
1653     }
1654   g_free (trashdir);
1655
1656   /* User specific trash didn't exist, can we create it? */
1657   res = g_access (topdir, W_OK) == 0;
1658   
1659   g_free (topdir);
1660   
1661   return res;
1662 }
1663
1664
1665 static gboolean
1666 g_local_file_trash (GFile         *file,
1667                     GCancellable  *cancellable,
1668                     GError       **error)
1669 {
1670   GLocalFile *local = G_LOCAL_FILE (file);
1671   struct stat file_stat, home_stat;
1672   const char *homedir;
1673   char *trashdir, *topdir, *infodir, *filesdir;
1674   char *basename, *trashname, *trashfile, *infoname, *infofile;
1675   char *original_name, *original_name_escaped;
1676   int i;
1677   char *data;
1678   gboolean is_homedir_trash;
1679   char delete_time[32];
1680   int fd;
1681   struct stat trash_stat, global_stat;
1682   char *dirname, *globaldir;
1683   
1684   if (g_lstat (local->filename, &file_stat) != 0)
1685     {
1686       int errsv = errno;
1687
1688       g_set_error (error, G_IO_ERROR,
1689                    g_io_error_from_errno (errsv),
1690                    _("Error trashing file: %s"),
1691                    g_strerror (errsv));
1692       return FALSE;
1693     }
1694     
1695   homedir = g_get_home_dir ();
1696   g_stat (homedir, &home_stat);
1697
1698   is_homedir_trash = FALSE;
1699   trashdir = NULL;
1700   if (file_stat.st_dev == home_stat.st_dev)
1701     {
1702       is_homedir_trash = TRUE;
1703       errno = 0;
1704       trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
1705       if (g_mkdir_with_parents (trashdir, 0700) < 0)
1706         {
1707           char *display_name;
1708           int errsv = errno;
1709
1710           display_name = g_filename_display_name (trashdir);
1711           g_set_error (error, G_IO_ERROR,
1712                        g_io_error_from_errno (errsv),
1713                        _("Unable to create trash dir %s: %s"),
1714                        display_name, g_strerror (errsv));
1715           g_free (display_name);
1716           g_free (trashdir);
1717           return FALSE;
1718         }
1719       topdir = g_strdup (g_get_user_data_dir ());
1720     }
1721   else
1722     {
1723       uid_t uid;
1724       char uid_str[32];
1725
1726       uid = geteuid ();
1727       g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
1728       
1729       topdir = find_topdir_for (local->filename);
1730       if (topdir == NULL)
1731         {
1732           g_set_error (error, G_IO_ERROR,
1733                        G_IO_ERROR_NOT_SUPPORTED,
1734                        _("Unable to find toplevel directory for trash"));
1735           return FALSE;
1736         }
1737       
1738       /* Try looking for global trash dir $topdir/.Trash/$uid */
1739       globaldir = g_build_filename (topdir, ".Trash", NULL);
1740       if (g_lstat (globaldir, &global_stat) == 0 &&
1741           S_ISDIR (global_stat.st_mode) &&
1742           (global_stat.st_mode & S_ISVTX) != 0)
1743         {
1744           trashdir = g_build_filename (globaldir, uid_str, NULL);
1745
1746           if (g_lstat (trashdir, &trash_stat) == 0)
1747             {
1748               if (!S_ISDIR (trash_stat.st_mode) ||
1749                   trash_stat.st_uid != uid)
1750                 {
1751                   /* Not a directory or not owned by user, ignore */
1752                   g_free (trashdir);
1753                   trashdir = NULL;
1754                 }
1755             }
1756           else if (g_mkdir (trashdir, 0700) == -1)
1757             {
1758               g_free (trashdir);
1759               trashdir = NULL;
1760             }
1761         }
1762       g_free (globaldir);
1763
1764       if (trashdir == NULL)
1765         {
1766           gboolean tried_create;
1767           
1768           /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
1769           dirname = g_strdup_printf (".Trash-%s", uid_str);
1770           trashdir = g_build_filename (topdir, dirname, NULL);
1771           g_free (dirname);
1772
1773           tried_create = FALSE;
1774
1775         retry:
1776           if (g_lstat (trashdir, &trash_stat) == 0)
1777             {
1778               if (!S_ISDIR (trash_stat.st_mode) ||
1779                   trash_stat.st_uid != uid)
1780                 {
1781                   /* Remove the failed directory */
1782                   if (tried_create)
1783                     g_remove (trashdir);
1784                   
1785                   /* Not a directory or not owned by user, ignore */
1786                   g_free (trashdir);
1787                   trashdir = NULL;
1788                 }
1789             }
1790           else
1791             {
1792               if (!tried_create &&
1793                   g_mkdir (trashdir, 0700) != -1)
1794                 {
1795                   /* Ensure that the created dir has the right uid etc.
1796                      This might fail on e.g. a FAT dir */
1797                   tried_create = TRUE;
1798                   goto retry;
1799                 }
1800               else
1801                 {
1802                   g_free (trashdir);
1803                   trashdir = NULL;
1804                 }
1805             }
1806         }
1807
1808       if (trashdir == NULL)
1809         {
1810           g_free (topdir);
1811           g_set_error (error, G_IO_ERROR,
1812                        G_IO_ERROR_NOT_SUPPORTED,
1813                        _("Unable to find or create trash directory"));
1814           return FALSE;
1815         }
1816     }
1817
1818   /* Trashdir points to the trash dir with the "info" and "files" subdirectories */
1819
1820   infodir = g_build_filename (trashdir, "info", NULL);
1821   filesdir = g_build_filename (trashdir, "files", NULL);
1822   g_free (trashdir);
1823
1824   /* Make sure we have the subdirectories */
1825   if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
1826       (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
1827     {
1828       g_free (topdir);
1829       g_free (infodir);
1830       g_free (filesdir);
1831       g_set_error (error, G_IO_ERROR,
1832                    G_IO_ERROR_NOT_SUPPORTED,
1833                    _("Unable to find or create trash directory"));
1834       return FALSE;
1835     }  
1836
1837   basename = g_path_get_basename (local->filename);
1838   i = 1;
1839   trashname = NULL;
1840   infofile = NULL;
1841   do {
1842     g_free (trashname);
1843     g_free (infofile);
1844     
1845     trashname = get_unique_filename (basename, i++);
1846     infoname = g_strconcat (trashname, ".trashinfo", NULL);
1847     infofile = g_build_filename (infodir, infoname, NULL);
1848     g_free (infoname);
1849
1850     fd = open (infofile, O_CREAT | O_EXCL, 0666);
1851   } while (fd == -1 && errno == EEXIST);
1852
1853   g_free (basename);
1854   g_free (infodir);
1855
1856   if (fd == -1)
1857     {
1858       int errsv = errno;
1859
1860       g_free (filesdir);
1861       g_free (topdir);
1862       g_free (trashname);
1863       g_free (infofile);
1864       
1865       g_set_error (error, G_IO_ERROR,
1866                    g_io_error_from_errno (errsv),
1867                    _("Unable to create trashing info file: %s"),
1868                    g_strerror (errsv));
1869       return FALSE;
1870     }
1871
1872   close (fd);
1873
1874   /* TODO: Maybe we should verify that you can delete the file from the trash
1875      before moving it? OTOH, that is hard, as it needs a recursive scan */
1876
1877   trashfile = g_build_filename (filesdir, trashname, NULL);
1878
1879   g_free (filesdir);
1880
1881   if (g_rename (local->filename, trashfile) == -1)
1882     {
1883       int errsv = errno;
1884
1885       g_free (topdir);
1886       g_free (trashname);
1887       g_free (infofile);
1888       g_free (trashfile);
1889       
1890       g_set_error (error, G_IO_ERROR,
1891                    g_io_error_from_errno (errsv),
1892                    _("Unable to trash file: %s"),
1893                    g_strerror (errsv));
1894       return FALSE;
1895     }
1896
1897   g_free (trashfile);
1898
1899   /* TODO: Do we need to update mtime/atime here after the move? */
1900
1901   /* Use absolute names for homedir */
1902   if (is_homedir_trash)
1903     original_name = g_strdup (local->filename);
1904   else
1905     original_name = try_make_relative (local->filename, topdir);
1906   original_name_escaped = escape_trash_name (original_name);
1907   
1908   g_free (original_name);
1909   g_free (topdir);
1910   
1911   {
1912     time_t t;
1913     struct tm now;
1914     t = time (NULL);
1915     localtime_r (&t, &now);
1916     delete_time[0] = 0;
1917     strftime(delete_time, sizeof (delete_time), "%Y-%m-%dT%H:%M:%S", &now);
1918   }
1919
1920   data = g_strdup_printf ("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
1921                           original_name_escaped, delete_time);
1922
1923   g_file_set_contents (infofile, data, -1, NULL);
1924   g_free (infofile);
1925   g_free (data);
1926   
1927   g_free (original_name_escaped);
1928   g_free (trashname);
1929   
1930   return TRUE;
1931 }
1932 #else /* G_OS_WIN32 */
1933 gboolean
1934 _g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
1935 {
1936   return FALSE;                 /* XXX ??? */
1937 }
1938
1939 static gboolean
1940 g_local_file_trash (GFile         *file,
1941                     GCancellable  *cancellable,
1942                     GError       **error)
1943 {
1944   GLocalFile *local = G_LOCAL_FILE (file);
1945   SHFILEOPSTRUCTW op = {0};
1946   gboolean success;
1947   wchar_t *wfilename;
1948   long len;
1949
1950   wfilename = g_utf8_to_utf16 (local->filename, -1, NULL, &len, NULL);
1951   /* SHFILEOPSTRUCT.pFrom is double-zero-terminated */
1952   wfilename = g_renew (wchar_t, wfilename, len + 2);
1953   wfilename[len + 1] = 0;
1954
1955   op.wFunc = FO_DELETE;
1956   op.pFrom = wfilename;
1957   op.fFlags = FOF_ALLOWUNDO;
1958
1959   success = SHFileOperationW (&op) == 0;
1960
1961   if (success && op.fAnyOperationsAborted)
1962     {
1963       if (cancellable && !g_cancellable_is_cancelled (cancellable))
1964         g_cancellable_cancel (cancellable);
1965       g_set_error (error, G_IO_ERROR,
1966                    G_IO_ERROR_CANCELLED,
1967                    _("Unable to trash file: %s"),
1968                    _("Operation was cancelled"));
1969       success = FALSE;
1970     }
1971   else if (!success)
1972     g_set_error (error, G_IO_ERROR,
1973                  G_IO_ERROR_FAILED,
1974                  _("Unable to trash file: %s"),
1975                  _("internal error"));
1976
1977   g_free (wfilename);
1978   return success;
1979 }
1980 #endif /* G_OS_WIN32 */
1981
1982 static gboolean
1983 g_local_file_make_directory (GFile         *file,
1984                              GCancellable  *cancellable,
1985                              GError       **error)
1986 {
1987   GLocalFile *local = G_LOCAL_FILE (file);
1988   
1989   if (g_mkdir (local->filename, 0755) == -1)
1990     {
1991       int errsv = errno;
1992
1993       if (errsv == EINVAL)
1994         /* This must be an invalid filename, on e.g. FAT */
1995         g_set_error (error, G_IO_ERROR,
1996                      G_IO_ERROR_INVALID_FILENAME,
1997                      _("Invalid filename"));
1998       else
1999         g_set_error (error, G_IO_ERROR,
2000                      g_io_error_from_errno (errsv),
2001                      _("Error creating directory: %s"),
2002                      g_strerror (errsv));
2003       return FALSE;
2004     }
2005   
2006   return TRUE;
2007 }
2008
2009 static gboolean
2010 g_local_file_make_symbolic_link (GFile         *file,
2011                                  const char    *symlink_value,
2012                                  GCancellable  *cancellable,
2013                                  GError       **error)
2014 {
2015 #ifdef HAVE_SYMLINK
2016   GLocalFile *local = G_LOCAL_FILE (file);
2017   
2018   if (symlink (symlink_value, local->filename) == -1)
2019     {
2020       int errsv = errno;
2021
2022       if (errsv == EINVAL)
2023         /* This must be an invalid filename, on e.g. FAT */
2024         g_set_error (error, G_IO_ERROR,
2025                      G_IO_ERROR_INVALID_FILENAME,
2026                      _("Invalid filename"));
2027       else
2028         g_set_error (error, G_IO_ERROR,
2029                      g_io_error_from_errno (errsv),
2030                      _("Error making symbolic link: %s"),
2031                      g_strerror (errsv));
2032       return FALSE;
2033     }
2034   return TRUE;
2035 #else
2036   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Symlinks not supported");
2037   return FALSE;
2038 #endif
2039 }
2040
2041
2042 static gboolean
2043 g_local_file_copy (GFile                  *source,
2044                    GFile                  *destination,
2045                    GFileCopyFlags          flags,
2046                    GCancellable           *cancellable,
2047                    GFileProgressCallback   progress_callback,
2048                    gpointer                progress_callback_data,
2049                    GError                **error)
2050 {
2051   /* Fall back to default copy */
2052   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Copy not supported");
2053   return FALSE;
2054 }
2055
2056 static gboolean
2057 g_local_file_move (GFile                  *source,
2058                    GFile                  *destination,
2059                    GFileCopyFlags          flags,
2060                    GCancellable           *cancellable,
2061                    GFileProgressCallback   progress_callback,
2062                    gpointer                progress_callback_data,
2063                    GError                **error)
2064 {
2065   GLocalFile *local_source, *local_destination;
2066   struct stat statbuf;
2067   gboolean destination_exist, source_is_dir;
2068   char *backup_name;
2069   int res;
2070   off_t source_size;
2071   
2072   if (!G_IS_LOCAL_FILE (source) ||
2073       !G_IS_LOCAL_FILE (destination))
2074     {
2075       /* Fall back to default move */
2076       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Move not supported");
2077       return FALSE;
2078     }
2079   
2080   local_source = G_LOCAL_FILE (source);
2081   local_destination = G_LOCAL_FILE (destination);
2082   
2083   res = g_lstat (local_source->filename, &statbuf);
2084   if (res == -1)
2085     {
2086       int errsv = errno;
2087
2088       g_set_error (error, G_IO_ERROR,
2089                    g_io_error_from_errno (errsv),
2090                    _("Error moving file: %s"),
2091                    g_strerror (errsv));
2092       return FALSE;
2093     }
2094
2095   source_is_dir = S_ISDIR (statbuf.st_mode);
2096   source_size = statbuf.st_size;
2097   
2098   destination_exist = FALSE;
2099   res = g_lstat (local_destination->filename, &statbuf);
2100   if (res == 0)
2101     {
2102       destination_exist = TRUE; /* Target file exists */
2103
2104       if (flags & G_FILE_COPY_OVERWRITE)
2105         {
2106           /* Always fail on dirs, even with overwrite */
2107           if (S_ISDIR (statbuf.st_mode))
2108             {
2109               if (source_is_dir)
2110                 g_set_error (error,
2111                              G_IO_ERROR,
2112                              G_IO_ERROR_WOULD_MERGE,
2113                              _("Can't move directory over directory"));
2114               else
2115                 g_set_error (error,
2116                              G_IO_ERROR,
2117                              G_IO_ERROR_IS_DIRECTORY,
2118                              _("Can't copy over directory"));
2119               return FALSE;
2120             }
2121         }
2122       else
2123         {
2124           g_set_error (error,
2125                        G_IO_ERROR,
2126                        G_IO_ERROR_EXISTS,
2127                        _("Target file exists"));
2128           return FALSE;
2129         }
2130     }
2131   
2132   if (flags & G_FILE_COPY_BACKUP && destination_exist)
2133     {
2134       backup_name = g_strconcat (local_destination->filename, "~", NULL);
2135       if (g_rename (local_destination->filename, backup_name) == -1)
2136         {
2137           g_set_error (error,
2138                        G_IO_ERROR,
2139                        G_IO_ERROR_CANT_CREATE_BACKUP,
2140                        _("Backup file creation failed"));
2141           g_free (backup_name);
2142           return FALSE;
2143         }
2144       g_free (backup_name);
2145       destination_exist = FALSE; /* It did, but no more */
2146     }
2147
2148   if (source_is_dir && destination_exist && (flags & G_FILE_COPY_OVERWRITE))
2149     {
2150       /* Source is a dir, destination exists (and is not a dir, because that would have failed
2151          earlier), and we're overwriting. Manually remove the target so we can do the rename. */
2152       res = g_unlink (local_destination->filename);
2153       if (res == -1)
2154         {
2155           int errsv = errno;
2156
2157           g_set_error (error, G_IO_ERROR,
2158                        g_io_error_from_errno (errsv),
2159                        _("Error removing target file: %s"),
2160                        g_strerror (errsv));
2161           return FALSE;
2162         }
2163     }
2164   
2165   if (g_rename (local_source->filename, local_destination->filename) == -1)
2166     {
2167       int errsv = errno;
2168
2169       if (errsv == EXDEV)
2170         /* This will cause the fallback code to run */
2171         g_set_error (error, G_IO_ERROR,
2172                      G_IO_ERROR_NOT_SUPPORTED,
2173                      _("Move between mounts not supported"));
2174       else if (errsv == EINVAL)
2175         /* This must be an invalid filename, on e.g. FAT, or
2176            we're trying to move the file into itself...
2177            We return invalid filename for both... */
2178         g_set_error (error, G_IO_ERROR,
2179                      G_IO_ERROR_INVALID_FILENAME,
2180                      _("Invalid filename"));
2181       else
2182         g_set_error (error, G_IO_ERROR,
2183                      g_io_error_from_errno (errsv),
2184                      _("Error moving file: %s"),
2185                      g_strerror (errsv));
2186       return FALSE;
2187     }
2188
2189   /* Make sure we send full copied size */
2190   if (progress_callback)
2191     progress_callback (source_size, source_size, progress_callback_data);
2192   
2193   return TRUE;
2194 }
2195
2196 static GFileMonitor*
2197 g_local_file_monitor_dir (GFile             *file,
2198                           GFileMonitorFlags  flags,
2199                           GCancellable      *cancellable,
2200                           GError           **error)
2201 {
2202   GLocalFile* local_file = G_LOCAL_FILE(file);
2203   return _g_local_directory_monitor_new (local_file->filename, flags, error);
2204 }
2205
2206 static GFileMonitor*
2207 g_local_file_monitor_file (GFile             *file,
2208                            GFileMonitorFlags  flags,
2209                            GCancellable      *cancellable,
2210                            GError           **error)
2211 {
2212   GLocalFile* local_file = G_LOCAL_FILE(file);
2213   return _g_local_file_monitor_new (local_file->filename, flags, error);
2214 }
2215
2216 static void
2217 g_local_file_file_iface_init (GFileIface *iface)
2218 {
2219   iface->dup = g_local_file_dup;
2220   iface->hash = g_local_file_hash;
2221   iface->equal = g_local_file_equal;
2222   iface->is_native = g_local_file_is_native;
2223   iface->has_uri_scheme = g_local_file_has_uri_scheme;
2224   iface->get_uri_scheme = g_local_file_get_uri_scheme;
2225   iface->get_basename = g_local_file_get_basename;
2226   iface->get_path = g_local_file_get_path;
2227   iface->get_uri = g_local_file_get_uri;
2228   iface->get_parse_name = g_local_file_get_parse_name;
2229   iface->get_parent = g_local_file_get_parent;
2230   iface->prefix_matches = g_local_file_prefix_matches;
2231   iface->get_relative_path = g_local_file_get_relative_path;
2232   iface->resolve_relative_path = g_local_file_resolve_relative_path;
2233   iface->get_child_for_display_name = g_local_file_get_child_for_display_name;
2234   iface->set_display_name = g_local_file_set_display_name;
2235   iface->enumerate_children = g_local_file_enumerate_children;
2236   iface->query_info = g_local_file_query_info;
2237   iface->query_filesystem_info = g_local_file_query_filesystem_info;
2238   iface->find_enclosing_mount = g_local_file_find_enclosing_mount;
2239   iface->query_settable_attributes = g_local_file_query_settable_attributes;
2240   iface->query_writable_namespaces = g_local_file_query_writable_namespaces;
2241   iface->set_attribute = g_local_file_set_attribute;
2242   iface->set_attributes_from_info = g_local_file_set_attributes_from_info;
2243   iface->read_fn = g_local_file_read;
2244   iface->append_to = g_local_file_append_to;
2245   iface->create = g_local_file_create;
2246   iface->replace = g_local_file_replace;
2247   iface->delete_file = g_local_file_delete;
2248   iface->trash = g_local_file_trash;
2249   iface->make_directory = g_local_file_make_directory;
2250   iface->make_symbolic_link = g_local_file_make_symbolic_link;
2251   iface->copy = g_local_file_copy;
2252   iface->move = g_local_file_move;
2253   iface->monitor_dir = g_local_file_monitor_dir;
2254   iface->monitor_file = g_local_file_monitor_file;
2255 }