Support for .hidden files
[platform/upstream/glib.git] / gio / glocalfileinfo.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  * 
5  * Copyright (C) 2006-2007 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Author: Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26
27 #ifdef HAVE_SYS_TIME_H
28 #include <sys/time.h>
29 #endif
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <fcntl.h>
37 #include <errno.h>
38 #ifdef HAVE_GRP_H
39 #include <grp.h>
40 #endif
41 #ifdef HAVE_PWD_H
42 #include <pwd.h>
43 #endif
44 #ifdef HAVE_SELINUX
45 #include <selinux/selinux.h>
46 #endif
47
48 #ifdef HAVE_XATTR
49
50 #if defined HAVE_SYS_XATTR_H
51   #include <sys/xattr.h>
52 #elif defined HAVE_ATTR_XATTR_H
53   #include <attr/xattr.h>
54 #else
55   #error "Neither <sys/xattr.h> nor <attr/xattr.h> is present but extended attribute support is enabled."
56 #endif /* defined HAVE_SYS_XATTR_H || HAVE_ATTR_XATTR_H */
57
58 #endif /* HAVE_XATTR */
59
60 #include <glib/gstdio.h>
61 #include <gfileattribute-priv.h>
62 #include <gfileinfo-priv.h>
63 #include <gvfs.h>
64
65 #ifndef G_OS_WIN32
66 #include "glib-private.h"
67 #endif
68 #include "glibintl.h"
69
70 #ifdef G_OS_WIN32
71 #include <windows.h>
72 #include <io.h>
73 #ifndef W_OK
74 #define W_OK 2
75 #endif
76 #ifndef R_OK
77 #define R_OK 4
78 #endif
79 #ifndef X_OK
80 #define X_OK 0 /* not really */
81 #endif
82 #ifndef S_ISREG
83 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
84 #endif
85 #ifndef S_ISDIR
86 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
87 #endif
88 #ifndef S_IXUSR
89 #define S_IXUSR _S_IEXEC
90 #endif
91 #endif
92
93 #include "glocalfileinfo.h"
94 #include "gioerror.h"
95 #include "gthemedicon.h"
96 #include "gcontenttypeprivate.h"
97
98
99 struct ThumbMD5Context {
100         guint32 buf[4];
101         guint32 bits[2];
102         unsigned char in[64];
103 };
104
105 #ifndef G_OS_WIN32
106
107 typedef struct {
108   char *user_name;
109   char *real_name;
110 } UidData;
111
112 G_LOCK_DEFINE_STATIC (uid_cache);
113 static GHashTable *uid_cache = NULL;
114
115 G_LOCK_DEFINE_STATIC (gid_cache);
116 static GHashTable *gid_cache = NULL;
117
118 #endif  /* !G_OS_WIN32 */
119
120 char *
121 _g_local_file_info_create_etag (GLocalFileStat *statbuf)
122 {
123   glong sec, usec;
124
125   sec = statbuf->st_mtime;
126 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
127   usec = statbuf->st_mtimensec / 1000;
128 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
129   usec = statbuf->st_mtim.tv_nsec / 1000;
130 #else
131   usec = 0;
132 #endif
133
134   return g_strdup_printf ("%lu:%lu", sec, usec);
135 }
136
137 static char *
138 _g_local_file_info_create_file_id (GLocalFileStat *statbuf)
139 {
140   return g_strdup_printf ("l%" G_GUINT64_FORMAT ":%" G_GUINT64_FORMAT,
141                           (guint64) statbuf->st_dev, 
142                           (guint64) statbuf->st_ino);
143 }
144
145 static char *
146 _g_local_file_info_create_fs_id (GLocalFileStat *statbuf)
147 {
148   return g_strdup_printf ("l%" G_GUINT64_FORMAT,
149                           (guint64) statbuf->st_dev);
150 }
151
152
153 #ifdef S_ISLNK
154
155 static gchar *
156 read_link (const gchar *full_name)
157 {
158 #ifdef HAVE_READLINK
159   gchar *buffer;
160   guint size;
161   
162   size = 256;
163   buffer = g_malloc (size);
164   
165   while (1)
166     {
167       int read_size;
168       
169       read_size = readlink (full_name, buffer, size);
170       if (read_size < 0)
171         {
172           g_free (buffer);
173           return NULL;
174         }
175       if (read_size < size)
176         {
177           buffer[read_size] = 0;
178           return buffer;
179         }
180       size *= 2;
181       buffer = g_realloc (buffer, size);
182     }
183 #else
184   return NULL;
185 #endif
186 }
187
188 #endif  /* S_ISLNK */
189
190 #ifdef HAVE_SELINUX
191 /* Get the SELinux security context */
192 static void
193 get_selinux_context (const char            *path,
194                      GFileInfo             *info,
195                      GFileAttributeMatcher *attribute_matcher,
196                      gboolean               follow_symlinks)
197 {
198   char *context;
199
200   if (!_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT))
201     return;
202   
203   if (is_selinux_enabled ())
204     {
205       if (follow_symlinks)
206         {
207           if (lgetfilecon_raw (path, &context) < 0)
208             return;
209         }
210       else
211         {
212           if (getfilecon_raw (path, &context) < 0)
213             return;
214         }
215
216       if (context)
217         {
218           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
219           freecon (context);
220         }
221     }
222 }
223 #endif
224
225 #ifdef HAVE_XATTR
226
227 /* Wrappers to hide away differences between (Linux) getxattr/lgetxattr and
228  * (Mac) getxattr(..., XATTR_NOFOLLOW)
229  */
230 #ifdef HAVE_XATTR_NOFOLLOW
231 #define g_fgetxattr(fd,name,value,size)  fgetxattr(fd,name,value,size,0,0)
232 #define g_flistxattr(fd,name,size)       flistxattr(fd,name,size,0)
233 #define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0,0)
234 #else
235 #define g_fgetxattr     fgetxattr
236 #define g_flistxattr    flistxattr
237 #define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0)
238 #endif
239
240 static ssize_t
241 g_getxattr (const char *path, const char *name, void *value, size_t size,
242             gboolean follow_symlinks)
243 {
244 #ifdef HAVE_XATTR_NOFOLLOW
245   return getxattr (path, name, value, size, 0, follow_symlinks ? 0 : XATTR_NOFOLLOW);
246 #else
247   if (follow_symlinks)
248     return getxattr (path, name, value, size);
249   else
250     return lgetxattr (path, name, value, size);
251 #endif
252 }
253
254 static ssize_t
255 g_listxattr(const char *path, char *namebuf, size_t size,
256             gboolean follow_symlinks)
257 {
258 #ifdef HAVE_XATTR_NOFOLLOW
259   return listxattr (path, namebuf, size, follow_symlinks ? 0 : XATTR_NOFOLLOW);
260 #else
261   if (follow_symlinks)
262     return listxattr (path, namebuf, size);
263   else
264     return llistxattr (path, namebuf, size);
265 #endif
266 }
267
268 static gboolean
269 valid_char (char c)
270 {
271   return c >= 32 && c <= 126 && c != '\\';
272 }
273
274 static gboolean
275 name_is_valid (const char *str)
276 {
277   while (*str)
278     {
279       if (!valid_char (*str++))
280         return FALSE;
281     }
282   return TRUE;
283 }
284
285 static char *
286 hex_escape_string (const char *str, 
287                    gboolean   *free_return)
288 {
289   int num_invalid, i;
290   char *escaped_str, *p;
291   unsigned char c;
292   static char *hex_digits = "0123456789abcdef";
293   int len;
294
295   len = strlen (str);
296   
297   num_invalid = 0;
298   for (i = 0; i < len; i++)
299     {
300       if (!valid_char (str[i]))
301         num_invalid++;
302     }
303
304   if (num_invalid == 0)
305     {
306       *free_return = FALSE;
307       return (char *)str;
308     }
309
310   escaped_str = g_malloc (len + num_invalid*3 + 1);
311
312   p = escaped_str;
313   for (i = 0; i < len; i++)
314     {
315       if (valid_char (str[i]))
316         *p++ = str[i];
317       else
318         {
319           c = str[i];
320           *p++ = '\\';
321           *p++ = 'x';
322           *p++ = hex_digits[(c >> 4) & 0xf];
323           *p++ = hex_digits[c & 0xf];
324         }
325     }
326   *p = 0;
327
328   *free_return = TRUE;
329   return escaped_str;
330 }
331
332 static char *
333 hex_unescape_string (const char *str, 
334                      int        *out_len, 
335                      gboolean   *free_return)
336 {
337   int i;
338   char *unescaped_str, *p;
339   unsigned char c;
340   int len;
341
342   len = strlen (str);
343   
344   if (strchr (str, '\\') == NULL)
345     {
346       if (out_len)
347         *out_len = len;
348       *free_return = FALSE;
349       return (char *)str;
350     }
351   
352   unescaped_str = g_malloc (len + 1);
353
354   p = unescaped_str;
355   for (i = 0; i < len; i++)
356     {
357       if (str[i] == '\\' &&
358           str[i+1] == 'x' &&
359           len - i >= 4)
360         {
361           c =
362             (g_ascii_xdigit_value (str[i+2]) << 4) |
363             g_ascii_xdigit_value (str[i+3]);
364           *p++ = c;
365           i += 3;
366         }
367       else
368         *p++ = str[i];
369     }
370   *p++ = 0;
371
372   if (out_len)
373     *out_len = p - unescaped_str;
374   *free_return = TRUE;
375   return unescaped_str;
376 }
377
378 static void
379 escape_xattr (GFileInfo  *info,
380               const char *gio_attr, /* gio attribute name */
381               const char *value, /* Is zero terminated */
382               size_t      len /* not including zero termination */)
383 {
384   char *escaped_val;
385   gboolean free_escaped_val;
386   
387   escaped_val = hex_escape_string (value, &free_escaped_val);
388   
389   g_file_info_set_attribute_string (info, gio_attr, escaped_val);
390   
391   if (free_escaped_val)
392     g_free (escaped_val);
393 }
394
395 static void
396 get_one_xattr (const char *path,
397                GFileInfo  *info,
398                const char *gio_attr,
399                const char *xattr,
400                gboolean    follow_symlinks)
401 {
402   char value[64];
403   char *value_p;
404   ssize_t len;
405
406   len = g_getxattr (path, xattr, value, sizeof (value)-1, follow_symlinks);
407
408   value_p = NULL;
409   if (len >= 0)
410     value_p = value;
411   else if (len == -1 && errno == ERANGE)
412     {
413       len = g_getxattr (path, xattr, NULL, 0, follow_symlinks);
414
415       if (len < 0)
416         return;
417
418       value_p = g_malloc (len+1);
419
420       len = g_getxattr (path, xattr, value_p, len, follow_symlinks);
421
422       if (len < 0)
423         {
424           g_free (value_p);
425           return;
426         }
427     }
428   else
429     return;
430   
431   /* Null terminate */
432   value_p[len] = 0;
433
434   escape_xattr (info, gio_attr, value_p, len);
435   
436   if (value_p != value)
437     g_free (value_p);
438 }
439
440 #endif /* defined HAVE_XATTR */
441
442 static void
443 get_xattrs (const char            *path,
444             gboolean               user,
445             GFileInfo             *info,
446             GFileAttributeMatcher *matcher,
447             gboolean               follow_symlinks)
448 {
449 #ifdef HAVE_XATTR
450   gboolean all;
451   gsize list_size;
452   ssize_t list_res_size;
453   size_t len;
454   char *list;
455   const char *attr, *attr2;
456
457   if (user)
458     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
459   else
460     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
461
462   if (all)
463     {
464       list_res_size = g_listxattr (path, NULL, 0, follow_symlinks);
465
466       if (list_res_size == -1 ||
467           list_res_size == 0)
468         return;
469
470       list_size = list_res_size;
471       list = g_malloc (list_size);
472
473     retry:
474       
475       list_res_size = g_listxattr (path, list, list_size, follow_symlinks);
476       
477       if (list_res_size == -1 && errno == ERANGE)
478         {
479           list_size = list_size * 2;
480           list = g_realloc (list, list_size);
481           goto retry;
482         }
483
484       if (list_res_size == -1)
485         return;
486
487       attr = list;
488       while (list_res_size > 0)
489         {
490           if ((user && g_str_has_prefix (attr, "user.")) ||
491               (!user && !g_str_has_prefix (attr, "user.")))
492             {
493               char *escaped_attr, *gio_attr;
494               gboolean free_escaped_attr;
495               
496               if (user)
497                 {
498                   escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
499                   gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
500                 }
501               else
502                 {
503                   escaped_attr = hex_escape_string (attr, &free_escaped_attr);
504                   gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
505                 }
506               
507               if (free_escaped_attr)
508                 g_free (escaped_attr);
509               
510               get_one_xattr (path, info, gio_attr, attr, follow_symlinks);
511
512               g_free (gio_attr);
513             }
514               
515           len = strlen (attr) + 1;
516           attr += len;
517           list_res_size -= len;
518         }
519
520       g_free (list);
521     }
522   else
523     {
524       while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
525         {
526           char *unescaped_attribute, *a;
527           gboolean free_unescaped_attribute;
528
529           attr2 = strchr (attr, ':');
530           if (attr2)
531             {
532               attr2 += 2; /* Skip '::' */
533               unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
534               if (user)
535                 a = g_strconcat ("user.", unescaped_attribute, NULL);
536               else
537                 a = unescaped_attribute;
538               
539               get_one_xattr (path, info, attr, a, follow_symlinks);
540
541               if (user)
542                 g_free (a);
543               
544               if (free_unescaped_attribute)
545                 g_free (unescaped_attribute);
546             }
547         }
548     }
549 #endif /* defined HAVE_XATTR */
550 }
551
552 #ifdef HAVE_XATTR
553 static void
554 get_one_xattr_from_fd (int         fd,
555                        GFileInfo  *info,
556                        const char *gio_attr,
557                        const char *xattr)
558 {
559   char value[64];
560   char *value_p;
561   ssize_t len;
562
563   len = g_fgetxattr (fd, xattr, value, sizeof (value) - 1);
564
565   value_p = NULL;
566   if (len >= 0)
567     value_p = value;
568   else if (len == -1 && errno == ERANGE)
569     {
570       len = g_fgetxattr (fd, xattr, NULL, 0);
571
572       if (len < 0)
573         return;
574
575       value_p = g_malloc (len + 1);
576
577       len = g_fgetxattr (fd, xattr, value_p, len);
578
579       if (len < 0)
580         {
581           g_free (value_p);
582           return;
583         }
584     }
585   else
586     return;
587   
588   /* Null terminate */
589   value_p[len] = 0;
590
591   escape_xattr (info, gio_attr, value_p, len);
592   
593   if (value_p != value)
594     g_free (value_p);
595 }
596 #endif /* defined HAVE_XATTR */
597
598 static void
599 get_xattrs_from_fd (int                    fd,
600                     gboolean               user,
601                     GFileInfo             *info,
602                     GFileAttributeMatcher *matcher)
603 {
604 #ifdef HAVE_XATTR
605   gboolean all;
606   gsize list_size;
607   ssize_t list_res_size;
608   size_t len;
609   char *list;
610   const char *attr, *attr2;
611
612   if (user)
613     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
614   else
615     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
616
617   if (all)
618     {
619       list_res_size = g_flistxattr (fd, NULL, 0);
620
621       if (list_res_size == -1 ||
622           list_res_size == 0)
623         return;
624
625       list_size = list_res_size;
626       list = g_malloc (list_size);
627
628     retry:
629       
630       list_res_size = g_flistxattr (fd, list, list_size);
631       
632       if (list_res_size == -1 && errno == ERANGE)
633         {
634           list_size = list_size * 2;
635           list = g_realloc (list, list_size);
636           goto retry;
637         }
638
639       if (list_res_size == -1)
640         return;
641
642       attr = list;
643       while (list_res_size > 0)
644         {
645           if ((user && g_str_has_prefix (attr, "user.")) ||
646               (!user && !g_str_has_prefix (attr, "user.")))
647             {
648               char *escaped_attr, *gio_attr;
649               gboolean free_escaped_attr;
650               
651               if (user)
652                 {
653                   escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
654                   gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
655                 }
656               else
657                 {
658                   escaped_attr = hex_escape_string (attr, &free_escaped_attr);
659                   gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
660                 }
661               
662               if (free_escaped_attr)
663                 g_free (escaped_attr);
664               
665               get_one_xattr_from_fd (fd, info, gio_attr, attr);
666             }
667           
668           len = strlen (attr) + 1;
669           attr += len;
670           list_res_size -= len;
671         }
672
673       g_free (list);
674     }
675   else
676     {
677       while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
678         {
679           char *unescaped_attribute, *a;
680           gboolean free_unescaped_attribute;
681
682           attr2 = strchr (attr, ':');
683           if (attr2)
684             {
685               attr2++; /* Skip ':' */
686               unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
687               if (user)
688                 a = g_strconcat ("user.", unescaped_attribute, NULL);
689               else
690                 a = unescaped_attribute;
691               
692               get_one_xattr_from_fd (fd, info, attr, a);
693
694               if (user)
695                 g_free (a);
696               
697               if (free_unescaped_attribute)
698                 g_free (unescaped_attribute);
699             }
700         }
701     }
702 #endif /* defined HAVE_XATTR */
703 }
704
705 #ifdef HAVE_XATTR
706 static gboolean
707 set_xattr (char                       *filename,
708            const char                 *escaped_attribute,
709            const GFileAttributeValue  *attr_value,
710            GError                    **error)
711 {
712   char *attribute, *value;
713   gboolean free_attribute, free_value;
714   int val_len, res, errsv;
715   gboolean is_user;
716   char *a;
717
718   if (attr_value == NULL)
719     {
720       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
721                            _("Attribute value must be non-NULL"));
722       return FALSE;
723     }
724
725   if (attr_value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
726     {
727       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
728                            _("Invalid attribute type (string expected)"));
729       return FALSE;
730     }
731
732   if (!name_is_valid (escaped_attribute))
733     {
734       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
735                            _("Invalid extended attribute name"));
736       return FALSE;
737     }
738
739   if (g_str_has_prefix (escaped_attribute, "xattr::"))
740     {
741       escaped_attribute += strlen ("xattr::");
742       is_user = TRUE;
743     }
744   else
745     {
746       g_warn_if_fail (g_str_has_prefix (escaped_attribute, "xattr-sys::"));
747       escaped_attribute += strlen ("xattr-sys::");
748       is_user = FALSE;
749     }
750   
751   attribute = hex_unescape_string (escaped_attribute, NULL, &free_attribute);
752   value = hex_unescape_string (attr_value->u.string, &val_len, &free_value);
753
754   if (is_user)
755     a = g_strconcat ("user.", attribute, NULL);
756   else
757     a = attribute;
758   
759   res = g_setxattr (filename, a, value, val_len);
760   errsv = errno;
761   
762   if (is_user)
763     g_free (a);
764   
765   if (free_attribute)
766     g_free (attribute);
767   
768   if (free_value)
769     g_free (value);
770
771   if (res == -1)
772     {
773       g_set_error (error, G_IO_ERROR,
774                    g_io_error_from_errno (errsv),
775                    _("Error setting extended attribute '%s': %s"),
776                    escaped_attribute, g_strerror (errsv));
777       return FALSE;
778     }
779   
780   return TRUE;
781 }
782
783 #endif
784
785
786 void
787 _g_local_file_info_get_parent_info (const char            *dir,
788                                     GFileAttributeMatcher *attribute_matcher,
789                                     GLocalParentFileInfo  *parent_info)
790 {
791   GStatBuf statbuf;
792   int res;
793
794   parent_info->extra_data = NULL;
795   parent_info->free_extra_data = NULL;
796   parent_info->writable = FALSE;
797   parent_info->is_sticky = FALSE;
798   parent_info->has_trash_dir = FALSE;
799   parent_info->device = 0;
800
801   if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME) ||
802       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE) ||
803       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH) ||
804       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT))
805     {
806       /* FIXME: Windows: The underlying _waccess() call in the C
807        * library is mostly pointless as it only looks at the READONLY
808        * FAT-style attribute of the file, it doesn't check the ACL at
809        * all.
810        */
811       parent_info->writable = (g_access (dir, W_OK) == 0);
812       
813       res = g_stat (dir, &statbuf);
814
815       /*
816        * The sticky bit (S_ISVTX) on a directory means that a file in that directory can be
817        * renamed or deleted only by the owner of the file, by the owner of the directory, and
818        * by a privileged process.
819        */
820       if (res == 0)
821         {
822 #ifdef S_ISVTX
823           parent_info->is_sticky = (statbuf.st_mode & S_ISVTX) != 0;
824 #else
825           parent_info->is_sticky = FALSE;
826 #endif
827           parent_info->owner = statbuf.st_uid;
828           parent_info->device = statbuf.st_dev;
829           /* No need to find trash dir if it's not writable anyway */
830           if (parent_info->writable &&
831               _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
832             parent_info->has_trash_dir = _g_local_file_has_trash_dir (dir, statbuf.st_dev);
833         }
834     }
835 }
836
837 void
838 _g_local_file_info_free_parent_info (GLocalParentFileInfo *parent_info)
839 {
840   if (parent_info->extra_data &&
841       parent_info->free_extra_data)
842     parent_info->free_extra_data (parent_info->extra_data);
843 }
844
845 static void
846 get_access_rights (GFileAttributeMatcher *attribute_matcher,
847                    GFileInfo             *info,
848                    const gchar           *path,
849                    GLocalFileStat        *statbuf,
850                    GLocalParentFileInfo  *parent_info)
851 {
852   /* FIXME: Windows: The underlyin _waccess() is mostly pointless */
853   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
854                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ))
855     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ,
856                                              g_access (path, R_OK) == 0);
857   
858   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
859                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE))
860     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE,
861                                              g_access (path, W_OK) == 0);
862   
863   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
864                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE))
865     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE,
866                                              g_access (path, X_OK) == 0);
867
868
869   if (parent_info)
870     {
871       gboolean writable;
872
873       writable = FALSE;
874       if (parent_info->writable)
875         {
876           if (parent_info->is_sticky)
877             {
878 #ifndef G_OS_WIN32
879               uid_t uid = geteuid ();
880
881               if (uid == statbuf->st_uid ||
882                   uid == parent_info->owner ||
883                   uid == 0)
884 #endif
885                 writable = TRUE;
886             }
887           else
888             writable = TRUE;
889         }
890
891       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME))
892         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME,
893                                                  writable);
894       
895       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE))
896         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE,
897                                                  writable);
898
899       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
900         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH,
901                                                  writable && parent_info->has_trash_dir);
902     }
903 }
904
905 static void
906 set_info_from_stat (GFileInfo             *info, 
907                     GLocalFileStat        *statbuf,
908                     GFileAttributeMatcher *attribute_matcher)
909 {
910   GFileType file_type;
911
912   file_type = G_FILE_TYPE_UNKNOWN;
913
914   if (S_ISREG (statbuf->st_mode))
915     file_type = G_FILE_TYPE_REGULAR;
916   else if (S_ISDIR (statbuf->st_mode))
917     file_type = G_FILE_TYPE_DIRECTORY;
918 #ifndef G_OS_WIN32
919   else if (S_ISCHR (statbuf->st_mode) ||
920            S_ISBLK (statbuf->st_mode) ||
921            S_ISFIFO (statbuf->st_mode)
922 #ifdef S_ISSOCK
923            || S_ISSOCK (statbuf->st_mode)
924 #endif
925            )
926     file_type = G_FILE_TYPE_SPECIAL;
927 #endif
928 #ifdef S_ISLNK
929   else if (S_ISLNK (statbuf->st_mode))
930     file_type = G_FILE_TYPE_SYMBOLIC_LINK;
931 #endif
932
933   g_file_info_set_file_type (info, file_type);
934   g_file_info_set_size (info, statbuf->st_size);
935
936   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_DEVICE, statbuf->st_dev);
937 #ifndef G_OS_WIN32
938   /* Pointless setting these on Windows even if they exist in the struct */
939   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_INODE, statbuf->st_ino);
940   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_NLINK, statbuf->st_nlink);
941   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_UID, statbuf->st_uid);
942   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_GID, statbuf->st_gid);
943   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_RDEV, statbuf->st_rdev);
944 #endif
945   /* FIXME: st_mode is mostly pointless on Windows, too. Set the attribute or not? */
946   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_MODE, statbuf->st_mode);
947 #if defined (HAVE_STRUCT_STAT_ST_BLKSIZE)
948   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCK_SIZE, statbuf->st_blksize);
949 #endif
950 #if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
951   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCKS, statbuf->st_blocks);
952   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_ALLOCATED_SIZE,
953                                           statbuf->st_blocks * G_GUINT64_CONSTANT (512));
954 #endif
955   
956   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED, statbuf->st_mtime);
957 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
958   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtimensec / 1000);
959 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
960   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtim.tv_nsec / 1000);
961 #endif
962   
963   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS, statbuf->st_atime);
964 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
965   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atimensec / 1000);
966 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
967   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atim.tv_nsec / 1000);
968 #endif
969   
970   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED, statbuf->st_ctime);
971 #if defined (HAVE_STRUCT_STAT_ST_CTIMENSEC)
972   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctimensec / 1000);
973 #elif defined (HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC)
974   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctim.tv_nsec / 1000);
975 #endif
976
977   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
978                                             G_FILE_ATTRIBUTE_ID_ETAG_VALUE))
979     {
980       char *etag = _g_local_file_info_create_etag (statbuf);
981       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ETAG_VALUE, etag);
982       g_free (etag);
983     }
984
985   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
986                                             G_FILE_ATTRIBUTE_ID_ID_FILE))
987     {
988       char *id = _g_local_file_info_create_file_id (statbuf);
989       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILE, id);
990       g_free (id);
991     }
992
993   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
994                                             G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM))
995     {
996       char *id = _g_local_file_info_create_fs_id (statbuf);
997       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM, id);
998       g_free (id);
999     }
1000 }
1001
1002 #ifndef G_OS_WIN32
1003
1004 static char *
1005 make_valid_utf8 (const char *name)
1006 {
1007   GString *string;
1008   const gchar *remainder, *invalid;
1009   gint remaining_bytes, valid_bytes;
1010   
1011   string = NULL;
1012   remainder = name;
1013   remaining_bytes = strlen (name);
1014   
1015   while (remaining_bytes != 0) 
1016     {
1017       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1018         break;
1019       valid_bytes = invalid - remainder;
1020     
1021       if (string == NULL) 
1022         string = g_string_sized_new (remaining_bytes);
1023
1024       g_string_append_len (string, remainder, valid_bytes);
1025       /* append U+FFFD REPLACEMENT CHARACTER */
1026       g_string_append (string, "\357\277\275");
1027       
1028       remaining_bytes -= valid_bytes + 1;
1029       remainder = invalid + 1;
1030     }
1031   
1032   if (string == NULL)
1033     return g_strdup (name);
1034   
1035   g_string_append (string, remainder);
1036
1037   g_warn_if_fail (g_utf8_validate (string->str, -1, NULL));
1038   
1039   return g_string_free (string, FALSE);
1040 }
1041
1042 static char *
1043 convert_pwd_string_to_utf8 (char *pwd_str)
1044 {
1045   char *utf8_string;
1046   
1047   if (!g_utf8_validate (pwd_str, -1, NULL))
1048     {
1049       utf8_string = g_locale_to_utf8 (pwd_str, -1, NULL, NULL, NULL);
1050       if (utf8_string == NULL)
1051         utf8_string = make_valid_utf8 (pwd_str);
1052     }
1053   else 
1054     utf8_string = g_strdup (pwd_str);
1055   
1056   return utf8_string;
1057 }
1058
1059 static void
1060 uid_data_free (UidData *data)
1061 {
1062   g_free (data->user_name);
1063   g_free (data->real_name);
1064   g_free (data);
1065 }
1066
1067 /* called with lock held */
1068 static UidData *
1069 lookup_uid_data (uid_t uid)
1070 {
1071   UidData *data;
1072   char buffer[4096];
1073   struct passwd pwbuf;
1074   struct passwd *pwbufp;
1075   char *gecos, *comma;
1076   
1077   if (uid_cache == NULL)
1078     uid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)uid_data_free);
1079
1080   data = g_hash_table_lookup (uid_cache, GINT_TO_POINTER (uid));
1081
1082   if (data)
1083     return data;
1084
1085   data = g_new0 (UidData, 1);
1086
1087 #if defined(HAVE_POSIX_GETPWUID_R)
1088   getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer), &pwbufp);
1089 #elif defined(HAVE_NONPOSIX_GETPWUID_R)
1090   pwbufp = getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer));
1091 #else
1092   pwbufp = getpwuid (uid);
1093 #endif
1094
1095   if (pwbufp != NULL)
1096     {
1097       if (pwbufp->pw_name != NULL && pwbufp->pw_name[0] != 0)
1098         data->user_name = convert_pwd_string_to_utf8 (pwbufp->pw_name);
1099
1100       gecos = pwbufp->pw_gecos;
1101
1102       if (gecos)
1103         {
1104           comma = strchr (gecos, ',');
1105           if (comma)
1106             *comma = 0;
1107           data->real_name = convert_pwd_string_to_utf8 (gecos);
1108         }
1109     }
1110
1111   /* Default fallbacks */
1112   if (data->real_name == NULL)
1113     {
1114       if (data->user_name != NULL)
1115         data->real_name = g_strdup (data->user_name);
1116       else
1117         data->real_name = g_strdup_printf ("user #%d", (int)uid);
1118     }
1119   
1120   if (data->user_name == NULL)
1121     data->user_name = g_strdup_printf ("%d", (int)uid);
1122   
1123   g_hash_table_replace (uid_cache, GINT_TO_POINTER (uid), data);
1124   
1125   return data;
1126 }
1127
1128 static char *
1129 get_username_from_uid (uid_t uid)
1130 {
1131   char *res;
1132   UidData *data;
1133   
1134   G_LOCK (uid_cache);
1135   data = lookup_uid_data (uid);
1136   res = g_strdup (data->user_name);  
1137   G_UNLOCK (uid_cache);
1138
1139   return res;
1140 }
1141
1142 static char *
1143 get_realname_from_uid (uid_t uid)
1144 {
1145   char *res;
1146   UidData *data;
1147   
1148   G_LOCK (uid_cache);
1149   data = lookup_uid_data (uid);
1150   res = g_strdup (data->real_name);  
1151   G_UNLOCK (uid_cache);
1152   
1153   return res;
1154 }
1155
1156 /* called with lock held */
1157 static char *
1158 lookup_gid_name (gid_t gid)
1159 {
1160   char *name;
1161   char buffer[4096];
1162   struct group gbuf;
1163   struct group *gbufp;
1164   
1165   if (gid_cache == NULL)
1166     gid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);
1167
1168   name = g_hash_table_lookup (gid_cache, GINT_TO_POINTER (gid));
1169
1170   if (name)
1171     return name;
1172
1173 #if defined (HAVE_POSIX_GETGRGID_R)
1174   getgrgid_r (gid, &gbuf, buffer, sizeof(buffer), &gbufp);
1175 #elif defined (HAVE_NONPOSIX_GETGRGID_R)
1176   gbufp = getgrgid_r (gid, &gbuf, buffer, sizeof(buffer));
1177 #else
1178   gbufp = getgrgid (gid);
1179 #endif
1180
1181   if (gbufp != NULL &&
1182       gbufp->gr_name != NULL &&
1183       gbufp->gr_name[0] != 0)
1184     name = convert_pwd_string_to_utf8 (gbufp->gr_name);
1185   else
1186     name = g_strdup_printf("%d", (int)gid);
1187   
1188   g_hash_table_replace (gid_cache, GINT_TO_POINTER (gid), name);
1189   
1190   return name;
1191 }
1192
1193 static char *
1194 get_groupname_from_gid (gid_t gid)
1195 {
1196   char *res;
1197   char *name;
1198   
1199   G_LOCK (gid_cache);
1200   name = lookup_gid_name (gid);
1201   res = g_strdup (name);  
1202   G_UNLOCK (gid_cache);
1203   return res;
1204 }
1205
1206 #endif /* !G_OS_WIN32 */
1207
1208 static char *
1209 get_content_type (const char          *basename,
1210                   const char          *path,
1211                   GLocalFileStat      *statbuf,
1212                   gboolean             is_symlink,
1213                   gboolean             symlink_broken,
1214                   GFileQueryInfoFlags  flags,
1215                   gboolean             fast)
1216 {
1217   if (is_symlink &&
1218       (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
1219     return g_strdup ("inode/symlink");
1220   else if (statbuf != NULL && S_ISDIR(statbuf->st_mode))
1221     return g_strdup ("inode/directory");
1222 #ifndef G_OS_WIN32
1223   else if (statbuf != NULL && S_ISCHR(statbuf->st_mode))
1224     return g_strdup ("inode/chardevice");
1225   else if (statbuf != NULL && S_ISBLK(statbuf->st_mode))
1226     return g_strdup ("inode/blockdevice");
1227   else if (statbuf != NULL && S_ISFIFO(statbuf->st_mode))
1228     return g_strdup ("inode/fifo");
1229 #endif
1230 #ifdef S_ISSOCK
1231   else if (statbuf != NULL && S_ISSOCK(statbuf->st_mode))
1232     return g_strdup ("inode/socket");
1233 #endif
1234   else
1235     {
1236       char *content_type;
1237       gboolean result_uncertain;
1238       
1239       content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
1240       
1241 #ifndef G_OS_WIN32
1242       if (!fast && result_uncertain && path != NULL)
1243         {
1244           guchar sniff_buffer[4096];
1245           gsize sniff_length;
1246           int fd;
1247
1248           sniff_length = _g_unix_content_type_get_sniff_len ();
1249           if (sniff_length > 4096)
1250             sniff_length = 4096;
1251
1252 #ifdef O_NOATIME          
1253           fd = g_open (path, O_RDONLY | O_NOATIME, 0);
1254           if (fd < 0 && errno == EPERM)
1255 #endif
1256             fd = g_open (path, O_RDONLY, 0);
1257
1258           if (fd != -1)
1259             {
1260               ssize_t res;
1261               
1262               res = read (fd, sniff_buffer, sniff_length);
1263               close (fd);
1264               if (res >= 0)
1265                 {
1266                   g_free (content_type);
1267                   content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
1268                 }
1269             }
1270         }
1271 #endif
1272       
1273       return content_type;
1274     }
1275   
1276 }
1277
1278 static void
1279 get_thumbnail_attributes (const char *path,
1280                           GFileInfo  *info)
1281 {
1282   GChecksum *checksum;
1283   char *uri;
1284   char *filename;
1285   char *basename;
1286
1287   uri = g_filename_to_uri (path, NULL, NULL);
1288
1289   checksum = g_checksum_new (G_CHECKSUM_MD5);
1290   g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1291   
1292   g_free (uri);
1293
1294   basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
1295   g_checksum_free (checksum);
1296
1297   filename = g_build_filename (g_get_user_cache_dir (),
1298                                "thumbnails", "large", basename,
1299                                NULL);
1300
1301   if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1302     _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1303   else
1304     {
1305       g_free (filename);
1306       filename = g_build_filename (g_get_user_cache_dir (),
1307                                    "thumbnails", "normal", basename,
1308                                    NULL);
1309
1310       if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1311         _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1312       else
1313         {
1314           g_free (filename);
1315           filename = g_build_filename (g_get_user_cache_dir (),
1316                                        "thumbnails", "fail",
1317                                        "gnome-thumbnail-factory",
1318                                        basename,
1319                                        NULL);
1320
1321           if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1322             _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAILING_FAILED, TRUE);
1323         }
1324     }
1325   g_free (basename);
1326   g_free (filename);
1327 }
1328
1329 #ifdef G_OS_WIN32
1330 static void
1331 win32_get_file_user_info (const gchar  *filename,
1332                           gchar       **group_name, 
1333                           gchar       **user_name, 
1334                           gchar       **real_name)
1335 {
1336   PSECURITY_DESCRIPTOR psd = NULL;
1337   DWORD sd_size = 0; /* first call calculates the size required */
1338   
1339   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1340   if ((GetFileSecurityW (wfilename, 
1341                         GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1342                         NULL,
1343                         sd_size,
1344                         &sd_size) || (ERROR_INSUFFICIENT_BUFFER == GetLastError())) &&
1345      (psd = g_try_malloc (sd_size)) != NULL &&
1346      GetFileSecurityW (wfilename, 
1347                        GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1348                        psd,
1349                        sd_size,
1350                        &sd_size))
1351     {
1352       PSID psid = 0;
1353       BOOL defaulted;
1354       SID_NAME_USE name_use = 0; /* don't care? */
1355       wchar_t *name = NULL;
1356       wchar_t *domain = NULL;
1357       DWORD name_len = 0;
1358       DWORD domain_len = 0;
1359       /* get the user name */
1360       do {
1361         if (!user_name)
1362           break;
1363         if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))
1364           break;
1365         if (!LookupAccountSidW (NULL, /* local machine */
1366                                 psid, 
1367                                 name, &name_len,
1368                                 domain, &domain_len, /* no domain info yet */
1369                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1370           break;
1371         name = g_try_malloc (name_len * sizeof (wchar_t));
1372         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1373         if (name && domain &&
1374             LookupAccountSidW (NULL, /* local machine */
1375                                psid, 
1376                                name, &name_len,
1377                                domain, &domain_len, /* no domain info yet */
1378                                &name_use))
1379           {
1380             *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1381           }
1382         g_free (name);
1383         g_free (domain);
1384       } while (FALSE);
1385
1386       /* get the group name */
1387       do {
1388         if (!group_name)
1389           break;
1390         if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))
1391           break;
1392         if (!LookupAccountSidW (NULL, /* local machine */
1393                                 psid, 
1394                                 name, &name_len,
1395                                 domain, &domain_len, /* no domain info yet */
1396                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1397           break;
1398         name = g_try_malloc (name_len * sizeof (wchar_t));
1399         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1400         if (name && domain &&
1401             LookupAccountSidW (NULL, /* local machine */
1402                                psid, 
1403                                name, &name_len,
1404                                domain, &domain_len, /* no domain info yet */
1405                                &name_use))
1406           {
1407             *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1408           }
1409         g_free (name);
1410         g_free (domain);
1411       } while (FALSE);
1412
1413       /* TODO: get real name */
1414
1415       g_free (psd);
1416     }
1417   g_free (wfilename);
1418 }
1419 #endif /* G_OS_WIN32 */
1420
1421 #ifndef G_OS_WIN32
1422 /* support for '.hidden' files */
1423 G_LOCK_DEFINE_STATIC (hidden_cache);
1424 static GHashTable *hidden_cache;
1425
1426 static gboolean
1427 remove_from_hidden_cache (gpointer user_data)
1428 {
1429   G_LOCK (hidden_cache);
1430   g_hash_table_remove (hidden_cache, user_data);
1431   G_UNLOCK (hidden_cache);
1432
1433   return FALSE;
1434 }
1435
1436 static GHashTable *
1437 read_hidden_file (const gchar *dirname)
1438 {
1439   gchar *filename;
1440   FILE *hidden;
1441
1442   filename = g_build_path ("/", dirname, ".hidden", NULL);
1443   hidden = fopen (filename, "r");
1444   g_free (filename);
1445
1446   if (hidden != NULL)
1447     {
1448       gchar buffer[PATH_MAX + 2]; /* \n\0 */
1449       GHashTable *table;
1450
1451       table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1452
1453       while (fgets (buffer, sizeof buffer, hidden))
1454         {
1455           gchar *newline;
1456
1457           if ((newline = strchr (buffer, '\n')) != NULL)
1458             {
1459               *newline++ = '\0';
1460
1461               g_hash_table_insert (table,
1462                                    g_memdup (buffer, newline - buffer),
1463                                    GINT_TO_POINTER (TRUE));
1464             }
1465         }
1466
1467       fclose (hidden);
1468
1469       return table;
1470     }
1471   else
1472     return NULL;
1473 }
1474
1475 static void
1476 maybe_unref_hash_table (gpointer data)
1477 {
1478   if (data != NULL)
1479     g_hash_table_unref (data);
1480 }
1481
1482 static gboolean
1483 file_is_hidden (const gchar *path,
1484                 const gchar *basename)
1485 {
1486   gboolean result;
1487   gchar *dirname;
1488   gpointer table;
1489
1490   dirname = g_path_get_dirname (path);
1491
1492   G_LOCK (hidden_cache);
1493
1494   if G_UNLIKELY (hidden_cache == NULL)
1495     hidden_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
1496                                           g_free, maybe_unref_hash_table);
1497
1498   if (!g_hash_table_lookup_extended (hidden_cache, dirname,
1499                                      NULL, &table))
1500     {
1501       gchar *mydirname;
1502       GSource *remove_from_cache_source;
1503
1504       g_hash_table_insert (hidden_cache,
1505                            mydirname = g_strdup (dirname),
1506                            table = read_hidden_file (dirname));
1507
1508       remove_from_cache_source = g_timeout_source_new_seconds (5);
1509       g_source_set_priority (remove_from_cache_source, G_PRIORITY_DEFAULT);
1510       g_source_set_callback (remove_from_cache_source, 
1511                              remove_from_hidden_cache, 
1512                              mydirname, 
1513                              NULL);
1514       g_source_attach (remove_from_cache_source, 
1515                        GLIB_PRIVATE_CALL (g_get_worker_context) ());
1516       g_source_unref (remove_from_cache_source);
1517     }
1518
1519   result = table != NULL &&
1520            GPOINTER_TO_INT (g_hash_table_lookup (table, basename));
1521
1522   G_UNLOCK (hidden_cache);
1523
1524   g_free (dirname);
1525
1526   return result;
1527 }
1528 #endif /* !G_OS_WIN32 */
1529
1530 void
1531 _g_local_file_info_get_nostat (GFileInfo              *info,
1532                                const char             *basename,
1533                                const char             *path,
1534                                GFileAttributeMatcher  *attribute_matcher)
1535 {
1536   g_file_info_set_name (info, basename);
1537
1538   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1539                                             G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
1540     {
1541       char *display_name = g_filename_display_basename (path);
1542      
1543       /* look for U+FFFD REPLACEMENT CHARACTER */ 
1544       if (strstr (display_name, "\357\277\275") != NULL)
1545         {
1546           char *p = display_name;
1547           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1548           g_free (p);
1549         }
1550       g_file_info_set_display_name (info, display_name);
1551       g_free (display_name);
1552     }
1553   
1554   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1555                                             G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
1556     {
1557       char *edit_name = g_filename_display_basename (path);
1558       g_file_info_set_edit_name (info, edit_name);
1559       g_free (edit_name);
1560     }
1561
1562   
1563   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1564                                             G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
1565     {
1566       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1567       if (copy_name)
1568         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
1569       g_free (copy_name);
1570     }
1571 }
1572
1573 static const char *
1574 get_icon_name (const char *path,
1575                gboolean    use_symbolic,
1576                gboolean   *with_fallbacks_out)
1577 {
1578   const char *name = NULL;
1579   gboolean with_fallbacks = TRUE;
1580
1581   if (strcmp (path, g_get_home_dir ()) == 0)
1582     {
1583       name = use_symbolic ? "user-home-symbolic" : "user-home";
1584       with_fallbacks = FALSE;
1585     }
1586   else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1587     {
1588       name = use_symbolic ? "user-desktop-symbolic" : "user-desktop";
1589       with_fallbacks = FALSE;
1590     }
1591   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
1592     {
1593       name = use_symbolic ? "folder-documents-symbolic" : "folder-documents";
1594     }
1595   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
1596     {
1597       name = use_symbolic ? "folder-download-symbolic" : "folder-download";
1598     }
1599   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
1600     {
1601       name = use_symbolic ? "folder-music-symbolic" : "folder-music";
1602     }
1603   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
1604     {
1605       name = use_symbolic ? "folder-pictures-symbolic" : "folder-pictures";
1606     }
1607   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
1608     {
1609       name = use_symbolic ? "folder-publicshare-symbolic" : "folder-publicshare";
1610     }
1611   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
1612     {
1613       name = use_symbolic ? "folder-templates-symbolic" : "folder-templates";
1614     }
1615   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
1616     {
1617       name = use_symbolic ? "folder-videos-symbolic" : "folder-videos";
1618     }
1619   else
1620     {
1621       name = NULL;
1622     }
1623
1624   if (with_fallbacks_out != NULL)
1625     *with_fallbacks_out = with_fallbacks;
1626
1627   return name;
1628 }
1629
1630 static GIcon *
1631 get_icon (const char *path,
1632           const char *content_type,
1633           gboolean    is_folder,
1634           gboolean    use_symbolic)
1635 {
1636   GIcon *icon = NULL;
1637   const char *icon_name;
1638   gboolean with_fallbacks;
1639
1640   icon_name = get_icon_name (path, use_symbolic, &with_fallbacks);
1641   if (icon_name != NULL)
1642     {
1643       if (with_fallbacks)
1644         icon = g_themed_icon_new_with_default_fallbacks (icon_name);
1645       else
1646         icon = g_themed_icon_new (icon_name);
1647     }
1648   else
1649     {
1650       if (use_symbolic)
1651         icon = g_content_type_get_symbolic_icon (content_type);
1652       else
1653         icon = g_content_type_get_icon (content_type);
1654
1655       if (G_IS_THEMED_ICON (icon) && is_folder)
1656         {
1657           g_themed_icon_append_name (G_THEMED_ICON (icon), use_symbolic ? "folder-symbolic" : "folder");
1658         }
1659     }
1660
1661   return icon;
1662 }
1663
1664 GFileInfo *
1665 _g_local_file_info_get (const char             *basename,
1666                         const char             *path,
1667                         GFileAttributeMatcher  *attribute_matcher,
1668                         GFileQueryInfoFlags     flags,
1669                         GLocalParentFileInfo   *parent_info,
1670                         GError                **error)
1671 {
1672   GFileInfo *info;
1673   GLocalFileStat statbuf;
1674 #ifdef S_ISLNK
1675   struct stat statbuf2;
1676 #endif
1677   int res;
1678   gboolean stat_ok;
1679   gboolean is_symlink, symlink_broken;
1680 #ifdef G_OS_WIN32
1681   DWORD dos_attributes;
1682 #endif
1683   char *symlink_target;
1684   GVfs *vfs;
1685   GVfsClass *class;
1686   guint64 device;
1687
1688   info = g_file_info_new ();
1689
1690   /* Make sure we don't set any unwanted attributes */
1691   g_file_info_set_attribute_mask (info, attribute_matcher);
1692   
1693   _g_local_file_info_get_nostat (info, basename, path, attribute_matcher);
1694
1695   if (attribute_matcher == NULL)
1696     {
1697       g_file_info_unset_attribute_mask (info);
1698       return info;
1699     }
1700
1701 #ifndef G_OS_WIN32
1702   res = g_lstat (path, &statbuf);
1703 #else
1704   {
1705     wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
1706     int len;
1707
1708     if (wpath == NULL)
1709       {
1710         g_object_unref (info);
1711         return NULL;
1712       }
1713
1714     len = wcslen (wpath);
1715     while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
1716       len--;
1717     if (len > 0 &&
1718         (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
1719       wpath[len] = '\0';
1720
1721     res = _wstati64 (wpath, &statbuf);
1722     dos_attributes = GetFileAttributesW (wpath);
1723
1724     g_free (wpath);
1725   }
1726 #endif
1727
1728   if (res == -1)
1729     {
1730       int errsv = errno;
1731
1732       /* Don't bail out if we get Permission denied (SELinux?) */
1733       if (errsv != EACCES)
1734         {
1735           char *display_name = g_filename_display_name (path);
1736           g_object_unref (info);
1737           g_set_error (error, G_IO_ERROR,
1738                        g_io_error_from_errno (errsv),
1739                        _("Error when getting information for file '%s': %s"),
1740                        display_name, g_strerror (errsv));
1741           g_free (display_name);
1742           return NULL;
1743         }
1744     }
1745
1746   /* Even if stat() fails, try to get as much as other attributes possible */
1747   stat_ok = res != -1;
1748
1749   if (stat_ok)
1750     device = statbuf.st_dev;
1751   else
1752     device = 0;
1753
1754 #ifdef S_ISLNK
1755   is_symlink = stat_ok && S_ISLNK (statbuf.st_mode);
1756 #else
1757   is_symlink = FALSE;
1758 #endif
1759   symlink_broken = FALSE;
1760 #ifdef S_ISLNK
1761   if (is_symlink)
1762     {
1763       g_file_info_set_is_symlink (info, TRUE);
1764
1765       /* Unless NOFOLLOW was set we default to following symlinks */
1766       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1767         {
1768           res = stat (path, &statbuf2);
1769
1770           /* Report broken links as symlinks */
1771           if (res != -1)
1772             {
1773               statbuf = statbuf2;
1774               stat_ok = TRUE;
1775             }
1776           else
1777             symlink_broken = TRUE;
1778         }
1779     }
1780 #endif
1781
1782   if (stat_ok)
1783     set_info_from_stat (info, &statbuf, attribute_matcher);
1784
1785 #ifndef G_OS_WIN32
1786   if (basename != NULL &&
1787       (basename[0] == '.' ||
1788        file_is_hidden (path, basename)))
1789     g_file_info_set_is_hidden (info, TRUE);
1790
1791   if (basename != NULL && basename[strlen (basename) -1] == '~' &&
1792       (stat_ok && S_ISREG (statbuf.st_mode)))
1793     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_IS_BACKUP, TRUE);
1794 #else
1795   if (dos_attributes & FILE_ATTRIBUTE_HIDDEN)
1796     g_file_info_set_is_hidden (info, TRUE);
1797
1798   if (dos_attributes & FILE_ATTRIBUTE_ARCHIVE)
1799     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_ARCHIVE, TRUE);
1800
1801   if (dos_attributes & FILE_ATTRIBUTE_SYSTEM)
1802     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_SYSTEM, TRUE);
1803 #endif
1804
1805   symlink_target = NULL;
1806 #ifdef S_ISLNK
1807   if (is_symlink)
1808     {
1809       symlink_target = read_link (path);
1810       if (symlink_target &&
1811           _g_file_attribute_matcher_matches_id (attribute_matcher,
1812                                                 G_FILE_ATTRIBUTE_ID_STANDARD_SYMLINK_TARGET))
1813         g_file_info_set_symlink_target (info, symlink_target);
1814     }
1815 #endif
1816   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1817                                             G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
1818       _g_file_attribute_matcher_matches_id (attribute_matcher,
1819                                             G_FILE_ATTRIBUTE_ID_STANDARD_ICON) ||
1820       _g_file_attribute_matcher_matches_id (attribute_matcher,
1821                                             G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1822     {
1823       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, FALSE);
1824
1825       if (content_type)
1826         {
1827           g_file_info_set_content_type (info, content_type);
1828
1829           if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1830                                                      G_FILE_ATTRIBUTE_ID_STANDARD_ICON)
1831                || _g_file_attribute_matcher_matches_id (attribute_matcher,
1832                                                         G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1833             {
1834               GIcon *icon;
1835
1836               /* non symbolic icon */
1837               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), FALSE);
1838               if (icon != NULL)
1839                 {
1840                   g_file_info_set_icon (info, icon);
1841                   g_object_unref (icon);
1842                 }
1843
1844               /* symbolic icon */
1845               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), TRUE);
1846               if (icon != NULL)
1847                 {
1848                   g_file_info_set_symbolic_icon (info, icon);
1849                   g_object_unref (icon);
1850                 }
1851
1852             }
1853           
1854           g_free (content_type);
1855         }
1856     }
1857
1858   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1859                                             G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))
1860     {
1861       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, TRUE);
1862       
1863       if (content_type)
1864         {
1865           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
1866           g_free (content_type);
1867         }
1868     }
1869
1870   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1871                                             G_FILE_ATTRIBUTE_ID_OWNER_USER))
1872     {
1873       char *name = NULL;
1874       
1875 #ifdef G_OS_WIN32
1876       win32_get_file_user_info (path, NULL, &name, NULL);
1877 #else
1878       if (stat_ok)
1879         name = get_username_from_uid (statbuf.st_uid);
1880 #endif
1881       if (name)
1882         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER, name);
1883       g_free (name);
1884     }
1885
1886   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1887                                             G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL))
1888     {
1889       char *name = NULL;
1890 #ifdef G_OS_WIN32
1891       win32_get_file_user_info (path, NULL, NULL, &name);
1892 #else
1893       if (stat_ok)
1894         name = get_realname_from_uid (statbuf.st_uid);
1895 #endif
1896       if (name)
1897         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL, name);
1898       g_free (name);
1899     }
1900   
1901   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1902                                             G_FILE_ATTRIBUTE_ID_OWNER_GROUP))
1903     {
1904       char *name = NULL;
1905 #ifdef G_OS_WIN32
1906       win32_get_file_user_info (path, &name, NULL, NULL);
1907 #else
1908       if (stat_ok)
1909         name = get_groupname_from_gid (statbuf.st_gid);
1910 #endif
1911       if (name)
1912         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_GROUP, name);
1913       g_free (name);
1914     }
1915
1916   if (stat_ok && parent_info && parent_info->device != 0 &&
1917       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT) &&
1918       statbuf.st_dev != parent_info->device) 
1919     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT, TRUE);
1920   
1921   if (stat_ok)
1922     get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1923   
1924 #ifdef HAVE_SELINUX
1925   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1926 #endif
1927   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1928   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1929
1930   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1931                                             G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH))
1932     get_thumbnail_attributes (path, info);
1933
1934   vfs = g_vfs_get_default ();
1935   class = G_VFS_GET_CLASS (vfs);
1936   if (class->local_file_add_info)
1937     {
1938       class->local_file_add_info (vfs,
1939                                   path,
1940                                   device,
1941                                   attribute_matcher,
1942                                   info,
1943                                   NULL,
1944                                   &parent_info->extra_data,
1945                                   &parent_info->free_extra_data);
1946     }
1947
1948   g_file_info_unset_attribute_mask (info);
1949
1950   g_free (symlink_target);
1951
1952   return info;
1953 }
1954
1955 GFileInfo *
1956 _g_local_file_info_get_from_fd (int         fd,
1957                                 const char *attributes,
1958                                 GError    **error)
1959 {
1960   GLocalFileStat stat_buf;
1961   GFileAttributeMatcher *matcher;
1962   GFileInfo *info;
1963   
1964 #ifdef G_OS_WIN32
1965 #define FSTAT _fstati64
1966 #else
1967 #define FSTAT fstat
1968 #endif
1969
1970   if (FSTAT (fd, &stat_buf) == -1)
1971     {
1972       int errsv = errno;
1973
1974       g_set_error (error, G_IO_ERROR,
1975                    g_io_error_from_errno (errsv),
1976                    _("Error when getting information for file descriptor: %s"),
1977                    g_strerror (errsv));
1978       return NULL;
1979     }
1980
1981   info = g_file_info_new ();
1982
1983   matcher = g_file_attribute_matcher_new (attributes);
1984
1985   /* Make sure we don't set any unwanted attributes */
1986   g_file_info_set_attribute_mask (info, matcher);
1987   
1988   set_info_from_stat (info, &stat_buf, matcher);
1989   
1990 #ifdef HAVE_SELINUX
1991   if (_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT) &&
1992       is_selinux_enabled ())
1993     {
1994       char *context;
1995       if (fgetfilecon_raw (fd, &context) >= 0)
1996         {
1997           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
1998           freecon (context);
1999         }
2000     }
2001 #endif
2002
2003   get_xattrs_from_fd (fd, TRUE, info, matcher);
2004   get_xattrs_from_fd (fd, FALSE, info, matcher);
2005   
2006   g_file_attribute_matcher_unref (matcher);
2007
2008   g_file_info_unset_attribute_mask (info);
2009   
2010   return info;
2011 }
2012
2013 static gboolean
2014 get_uint32 (const GFileAttributeValue  *value,
2015             guint32                    *val_out,
2016             GError                    **error)
2017 {
2018   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
2019     {
2020       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2021                            _("Invalid attribute type (uint32 expected)"));
2022       return FALSE;
2023     }
2024
2025   *val_out = value->u.uint32;
2026   
2027   return TRUE;
2028 }
2029
2030 #ifdef HAVE_UTIMES
2031 static gboolean
2032 get_uint64 (const GFileAttributeValue  *value,
2033             guint64                    *val_out,
2034             GError                    **error)
2035 {
2036   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
2037     {
2038       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2039                            _("Invalid attribute type (uint64 expected)"));
2040       return FALSE;
2041     }
2042
2043   *val_out = value->u.uint64;
2044   
2045   return TRUE;
2046 }
2047 #endif
2048
2049 #if defined(HAVE_SYMLINK)
2050 static gboolean
2051 get_byte_string (const GFileAttributeValue  *value,
2052                  const char                **val_out,
2053                  GError                    **error)
2054 {
2055   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_STRING)
2056     {
2057       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2058                            _("Invalid attribute type (byte string expected)"));
2059       return FALSE;
2060     }
2061
2062   *val_out = value->u.string;
2063   
2064   return TRUE;
2065 }
2066 #endif
2067
2068 #ifdef HAVE_SELINUX
2069 static gboolean
2070 get_string (const GFileAttributeValue  *value,
2071             const char                **val_out,
2072             GError                    **error)
2073 {
2074   if (value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
2075     {
2076       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2077                            _("Invalid attribute type (byte string expected)"));
2078       return FALSE;
2079     }
2080
2081   *val_out = value->u.string;
2082   
2083   return TRUE;
2084 }
2085 #endif
2086
2087 static gboolean
2088 set_unix_mode (char                       *filename,
2089                GFileQueryInfoFlags         flags,
2090                const GFileAttributeValue  *value,
2091                GError                    **error)
2092 {
2093   guint32 val = 0;
2094   int res = 0;
2095   
2096   if (!get_uint32 (value, &val, error))
2097     return FALSE;
2098
2099 #ifdef HAVE_SYMLINK
2100   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) {
2101 #ifdef HAVE_LCHMOD
2102     res = lchmod (filename, val);
2103 #else
2104     struct stat statbuf;
2105     /* Calling chmod on a symlink changes permissions on the symlink.
2106      * We don't want to do this, so we need to check for a symlink */
2107     res = g_lstat (filename, &statbuf);
2108     if (res == 0 && S_ISLNK (statbuf.st_mode))
2109       {
2110         g_set_error_literal (error, G_IO_ERROR,
2111                              G_IO_ERROR_NOT_SUPPORTED,
2112                              _("Cannot set permissions on symlinks"));
2113         return FALSE;
2114       }
2115     else if (res == 0)
2116       res = g_chmod (filename, val);
2117 #endif
2118   } else
2119 #endif
2120     res = g_chmod (filename, val);
2121
2122   if (res == -1)
2123     {
2124       int errsv = errno;
2125
2126       g_set_error (error, G_IO_ERROR,
2127                    g_io_error_from_errno (errsv),
2128                    _("Error setting permissions: %s"),
2129                    g_strerror (errsv));
2130       return FALSE;
2131     }
2132   return TRUE;
2133 }
2134
2135 #ifdef HAVE_CHOWN
2136 static gboolean
2137 set_unix_uid_gid (char                       *filename,
2138                   const GFileAttributeValue  *uid_value,
2139                   const GFileAttributeValue  *gid_value,
2140                   GFileQueryInfoFlags         flags,
2141                   GError                    **error)
2142 {
2143   int res;
2144   guint32 val = 0;
2145   uid_t uid;
2146   gid_t gid;
2147   
2148   if (uid_value)
2149     {
2150       if (!get_uint32 (uid_value, &val, error))
2151         return FALSE;
2152       uid = val;
2153     }
2154   else
2155     uid = -1;
2156   
2157   if (gid_value)
2158     {
2159       if (!get_uint32 (gid_value, &val, error))
2160         return FALSE;
2161       gid = val;
2162     }
2163   else
2164     gid = -1;
2165   
2166 #ifdef HAVE_LCHOWN
2167   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
2168     res = lchown (filename, uid, gid);
2169   else
2170 #endif
2171     res = chown (filename, uid, gid);
2172   
2173   if (res == -1)
2174     {
2175       int errsv = errno;
2176
2177       g_set_error (error, G_IO_ERROR,
2178                    g_io_error_from_errno (errsv),
2179                    _("Error setting owner: %s"),
2180                    g_strerror (errsv));
2181           return FALSE;
2182     }
2183   return TRUE;
2184 }
2185 #endif
2186
2187 #ifdef HAVE_SYMLINK
2188 static gboolean
2189 set_symlink (char                       *filename,
2190              const GFileAttributeValue  *value,
2191              GError                    **error)
2192 {
2193   const char *val;
2194   struct stat statbuf;
2195   
2196   if (!get_byte_string (value, &val, error))
2197     return FALSE;
2198   
2199   if (val == NULL)
2200     {
2201       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2202                            _("symlink must be non-NULL"));
2203       return FALSE;
2204     }
2205   
2206   if (g_lstat (filename, &statbuf))
2207     {
2208       int errsv = errno;
2209
2210       g_set_error (error, G_IO_ERROR,
2211                    g_io_error_from_errno (errsv),
2212                    _("Error setting symlink: %s"),
2213                    g_strerror (errsv));
2214       return FALSE;
2215     }
2216   
2217   if (!S_ISLNK (statbuf.st_mode))
2218     {
2219       g_set_error_literal (error, G_IO_ERROR,
2220                            G_IO_ERROR_NOT_SYMBOLIC_LINK,
2221                            _("Error setting symlink: file is not a symlink"));
2222       return FALSE;
2223     }
2224   
2225   if (g_unlink (filename))
2226     {
2227       int errsv = errno;
2228
2229       g_set_error (error, G_IO_ERROR,
2230                    g_io_error_from_errno (errsv),
2231                    _("Error setting symlink: %s"),
2232                    g_strerror (errsv));
2233       return FALSE;
2234     }
2235   
2236   if (symlink (filename, val) != 0)
2237     {
2238       int errsv = errno;
2239
2240       g_set_error (error, G_IO_ERROR,
2241                    g_io_error_from_errno (errsv),
2242                    _("Error setting symlink: %s"),
2243                    g_strerror (errsv));
2244       return FALSE;
2245     }
2246   
2247   return TRUE;
2248 }
2249 #endif
2250
2251 #ifdef HAVE_UTIMES
2252 static int
2253 lazy_stat (char        *filename, 
2254            struct stat *statbuf, 
2255            gboolean    *called_stat)
2256 {
2257   int res;
2258
2259   if (*called_stat)
2260     return 0;
2261   
2262   res = g_stat (filename, statbuf);
2263   
2264   if (res == 0)
2265     *called_stat = TRUE;
2266   
2267   return res;
2268 }
2269
2270
2271 static gboolean
2272 set_mtime_atime (char                       *filename,
2273                  const GFileAttributeValue  *mtime_value,
2274                  const GFileAttributeValue  *mtime_usec_value,
2275                  const GFileAttributeValue  *atime_value,
2276                  const GFileAttributeValue  *atime_usec_value,
2277                  GError                    **error)
2278 {
2279   int res;
2280   guint64 val = 0;
2281   guint32 val_usec = 0;
2282   struct stat statbuf;
2283   gboolean got_stat = FALSE;
2284   struct timeval times[2] = { {0, 0}, {0, 0} };
2285
2286   /* ATIME */
2287   if (atime_value)
2288     {
2289       if (!get_uint64 (atime_value, &val, error))
2290         return FALSE;
2291       times[0].tv_sec = val;
2292     }
2293   else
2294     {
2295       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2296         {
2297           times[0].tv_sec = statbuf.st_mtime;
2298 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
2299           times[0].tv_usec = statbuf.st_atimensec / 1000;
2300 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2301           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
2302 #endif
2303         }
2304     }
2305   
2306   if (atime_usec_value)
2307     {
2308       if (!get_uint32 (atime_usec_value, &val_usec, error))
2309         return FALSE;
2310       times[0].tv_usec = val_usec;
2311     }
2312
2313   /* MTIME */
2314   if (mtime_value)
2315     {
2316       if (!get_uint64 (mtime_value, &val, error))
2317         return FALSE;
2318       times[1].tv_sec = val;
2319     }
2320   else
2321     {
2322       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2323         {
2324           times[1].tv_sec = statbuf.st_mtime;
2325 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
2326           times[1].tv_usec = statbuf.st_mtimensec / 1000;
2327 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
2328           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
2329 #endif
2330         }
2331     }
2332   
2333   if (mtime_usec_value)
2334     {
2335       if (!get_uint32 (mtime_usec_value, &val_usec, error))
2336         return FALSE;
2337       times[1].tv_usec = val_usec;
2338     }
2339   
2340   res = utimes (filename, times);
2341   if (res == -1)
2342     {
2343       int errsv = errno;
2344
2345       g_set_error (error, G_IO_ERROR,
2346                    g_io_error_from_errno (errsv),
2347                    _("Error setting modification or access time: %s"),
2348                    g_strerror (errsv));
2349           return FALSE;
2350     }
2351   return TRUE;
2352 }
2353 #endif
2354
2355
2356 #ifdef HAVE_SELINUX
2357 static gboolean
2358 set_selinux_context (char                       *filename,
2359                  const GFileAttributeValue  *value,
2360                  GError                    **error)
2361 {
2362   const char *val;
2363
2364   if (!get_string (value, &val, error))
2365     return FALSE;
2366
2367   if (val == NULL)
2368   {
2369     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2370                          _("SELinux context must be non-NULL"));
2371     return FALSE;
2372   }
2373
2374   if (is_selinux_enabled ()) {
2375         security_context_t val_s;
2376         
2377         val_s = g_strdup (val);
2378         
2379         if (setfilecon_raw (filename, val_s) < 0)
2380         {
2381             int errsv = errno;
2382             
2383             g_set_error (error, G_IO_ERROR,
2384                          g_io_error_from_errno (errsv),
2385                         _("Error setting SELinux context: %s"),
2386                          g_strerror (errsv));
2387             return FALSE;
2388         }
2389         g_free (val_s);
2390   } else {
2391     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2392                          _("SELinux is not enabled on this system"));
2393     return FALSE;
2394   }
2395                                                      
2396   return TRUE;
2397 }
2398 #endif 
2399
2400
2401 gboolean
2402 _g_local_file_info_set_attribute (char                 *filename,
2403                                   const char           *attribute,
2404                                   GFileAttributeType    type,
2405                                   gpointer              value_p,
2406                                   GFileQueryInfoFlags   flags,
2407                                   GCancellable         *cancellable,
2408                                   GError              **error)
2409 {
2410   GFileAttributeValue value = { 0 };
2411   GVfsClass *class;
2412   GVfs *vfs;
2413
2414   _g_file_attribute_value_set_from_pointer (&value, type, value_p, FALSE);
2415   
2416   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
2417     return set_unix_mode (filename, flags, &value, error);
2418   
2419 #ifdef HAVE_CHOWN
2420   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
2421     return set_unix_uid_gid (filename, &value, NULL, flags, error);
2422   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
2423     return set_unix_uid_gid (filename, NULL, &value, flags, error);
2424 #endif
2425   
2426 #ifdef HAVE_SYMLINK
2427   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET) == 0)
2428     return set_symlink (filename, &value, error);
2429 #endif
2430
2431 #ifdef HAVE_UTIMES
2432   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
2433     return set_mtime_atime (filename, &value, NULL, NULL, NULL, error);
2434   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
2435     return set_mtime_atime (filename, NULL, &value, NULL, NULL, error);
2436   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
2437     return set_mtime_atime (filename, NULL, NULL, &value, NULL, error);
2438   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
2439     return set_mtime_atime (filename, NULL, NULL, NULL, &value, error);
2440 #endif
2441
2442 #ifdef HAVE_XATTR
2443   else if (g_str_has_prefix (attribute, "xattr::"))
2444     return set_xattr (filename, attribute, &value, error);
2445   else if (g_str_has_prefix (attribute, "xattr-sys::"))
2446     return set_xattr (filename, attribute, &value, error);
2447 #endif
2448
2449 #ifdef HAVE_SELINUX 
2450   else if (strcmp (attribute, G_FILE_ATTRIBUTE_SELINUX_CONTEXT) == 0)
2451     return set_selinux_context (filename, &value, error);
2452 #endif
2453
2454   vfs = g_vfs_get_default ();
2455   class = G_VFS_GET_CLASS (vfs);
2456   if (class->local_file_set_attributes)
2457     {
2458       GFileInfo *info;
2459
2460       info = g_file_info_new ();
2461       g_file_info_set_attribute (info,
2462                                  attribute,
2463                                  type,
2464                                  value_p);
2465       if (!class->local_file_set_attributes (vfs, filename,
2466                                              info,
2467                                              flags, cancellable,
2468                                              error))
2469         {
2470           g_object_unref (info);
2471           return FALSE;
2472         }
2473
2474       if (g_file_info_get_attribute_status (info, attribute) == G_FILE_ATTRIBUTE_STATUS_SET)
2475         {
2476           g_object_unref (info);
2477           return TRUE;
2478         }
2479
2480       g_object_unref (info);
2481     }
2482
2483   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2484                _("Setting attribute %s not supported"), attribute);
2485   return FALSE;
2486 }
2487
2488 gboolean
2489 _g_local_file_info_set_attributes  (char                 *filename,
2490                                     GFileInfo            *info,
2491                                     GFileQueryInfoFlags   flags,
2492                                     GCancellable         *cancellable,
2493                                     GError              **error)
2494 {
2495   GFileAttributeValue *value;
2496 #ifdef HAVE_CHOWN
2497   GFileAttributeValue *uid, *gid;
2498 #endif
2499 #ifdef HAVE_UTIMES
2500   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
2501 #endif
2502 #if defined (HAVE_CHOWN) || defined (HAVE_UTIMES)
2503   GFileAttributeStatus status;
2504 #endif
2505   gboolean res;
2506   GVfsClass *class;
2507   GVfs *vfs;
2508   
2509   /* Handles setting multiple specified data in a single set, and takes care
2510      of ordering restrictions when setting attributes */
2511
2512   res = TRUE;
2513
2514   /* Set symlink first, since this recreates the file */
2515 #ifdef HAVE_SYMLINK
2516   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
2517   if (value)
2518     {
2519       if (!set_symlink (filename, value, error))
2520         {
2521           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2522           res = FALSE;
2523           /* Don't set error multiple times */
2524           error = NULL;
2525         }
2526       else
2527         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2528         
2529     }
2530 #endif
2531
2532 #ifdef HAVE_CHOWN
2533   /* Group uid and gid setting into one call
2534    * Change ownership before permissions, since ownership changes can
2535      change permissions (e.g. setuid)
2536    */
2537   uid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_UID);
2538   gid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_GID);
2539   
2540   if (uid || gid)
2541     {
2542       if (!set_unix_uid_gid (filename, uid, gid, flags, error))
2543         {
2544           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2545           res = FALSE;
2546           /* Don't set error multiple times */
2547           error = NULL;
2548         }
2549       else
2550         status = G_FILE_ATTRIBUTE_STATUS_SET;
2551       if (uid)
2552         uid->status = status;
2553       if (gid)
2554         gid->status = status;
2555     }
2556 #endif
2557   
2558   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2559   if (value)
2560     {
2561       if (!set_unix_mode (filename, flags, value, error))
2562         {
2563           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2564           res = FALSE;
2565           /* Don't set error multiple times */
2566           error = NULL;
2567         }
2568       else
2569         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2570         
2571     }
2572
2573 #ifdef HAVE_UTIMES
2574   /* Group all time settings into one call
2575    * Change times as the last thing to avoid it changing due to metadata changes
2576    */
2577   
2578   mtime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2579   mtime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2580   atime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2581   atime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2582
2583   if (mtime || mtime_usec || atime || atime_usec)
2584     {
2585       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2586         {
2587           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2588           res = FALSE;
2589           /* Don't set error multiple times */
2590           error = NULL;
2591         }
2592       else
2593         status = G_FILE_ATTRIBUTE_STATUS_SET;
2594       
2595       if (mtime)
2596         mtime->status = status;
2597       if (mtime_usec)
2598         mtime_usec->status = status;
2599       if (atime)
2600         atime->status = status;
2601       if (atime_usec)
2602         atime_usec->status = status;
2603     }
2604 #endif
2605
2606   /* xattrs are handled by default callback */
2607
2608
2609   /*  SELinux context */
2610 #ifdef HAVE_SELINUX 
2611   if (is_selinux_enabled ()) {
2612     value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_SELINUX_CONTEXT);
2613     if (value)
2614     {
2615       if (!set_selinux_context (filename, value, error))
2616         {
2617           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2618           res = FALSE;
2619           /* Don't set error multiple times */
2620           error = NULL;
2621         }
2622       else
2623         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2624     }
2625   }
2626 #endif
2627
2628   vfs = g_vfs_get_default ();
2629   class = G_VFS_GET_CLASS (vfs);
2630   if (class->local_file_set_attributes)
2631     {
2632       if (!class->local_file_set_attributes (vfs, filename,
2633                                              info,
2634                                              flags, cancellable,
2635                                              error))
2636         {
2637           res = FALSE;
2638           /* Don't set error multiple times */
2639           error = NULL;
2640         }
2641     }
2642
2643   return res;
2644 }