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