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