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