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