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