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